Create a random string of digits - sql-server

I need to create a random string of digits of given length
CREATE FUNCTION UniqConvert
(#calue as varchar(max),
#len as int)
The output should be of the length #len
and should be unique per input #value
I already asked similar question:
Create random string of digits T-SQL
This one has different concept

declare #len int
set #len = 3
DECLARE #Random INT
DECLARE #Upper INT
DECLARE #Lower INT
SET #Lower = power(10,#Len-1) ---- The lowest random number
SET #Upper = power(10,#Len )-1 ---- The highest random number
SELECT #Random = ROUND(((#Upper - #Lower -1) * RAND() + #Lower), 0)
select #Random

Try this
select Cast(Round(Rand()*power(10,#Len),0) as Varchar(30))

Related

Generate a string format based on fixed length and numeric units on each increment

I had to write a SP to generate a string with the combination of Country (7 chars) + Province (1 char) + numeric number starts from 01. for eg: JAMAICAK01
where JAMAICA (Country) , K (Province) and 01 is the numeric number that gets incremented by 1 for each transaction.
The issue I have here is the generated string length max is 10, can be lesser than 10 but not >10.
It should be handled in a way with certain rules like
the combination don't exist
When the numeric unit changes from tens to hundreds making the string
length >10, I need to remove the right chars for eg JAMAICAKKK10 to
JAMAICAK10 from the right to make the total max length 10.
In my code below I tried to check if the combination exists and I get the max of it and do the numeric increment from the last one. think it can be done in a better way.
Declare #Province char(2)
Declare #Country varchar(10)
declare #CounProv varchar(10)
Declare #SimilarCounPRov varchar(max) = '';
declare #FinalString nvarchar(12)
declare #s varchar(50)
declare #s1 varchar(50)
declare #s2 varchar(50)
Set #Province = LEFT('KINGSTON', 1)
Set #Country = LEFT('JAMAICA', 7)
Set #CounProv = #Country+#Province
Select #SimilarCounPRov = MAX(field1) from dbo.table where field1
LIKE '%JAMAICAK%'
if #SimilarCounPRov IS NOT NULL
BEGIN
Set #s = (select fn_AlphaOnly('%JAMAICAK99%')) -- returns JAMAICAK
Set #s1 = (select fn_NumericOnly('%JAMAICAK99%')) -- returns 199
set #s2= #s1 +1 -- increment by 1
if len(#FinalString) > 10
----
need help here----`
I'm not sure that I understood all your requirements but if you need to generate strings like : JAMAICAK1,JAMAICAK2,...JAMAICAK10...,JAMAICAK11,...JAMAICA100,JAMAICA101,...JAMAIC1000,JAMAIC1001...
You can try to exploit this piece of code :
Declare #Province char(2)
Declare #Country varchar(10)
Declare #CounProv varchar(10)
Declare #value int
Declare #str_value VARCHAR(100)
Set #Province = LEFT('KINGSTON', 1)
Set #Country = LEFT('JAMAICA', 7)
Set #value = 999999
Set #CounProv = #Country+#Province
Set #str_value = (select CAST(#value AS varchar(100)))
select LEFT(#CounProv,10-LEN(#str_value))+#str_value
Tell me if it helps.

update value based on row number?

i'm pretty new to SQL and stored procedures and i'm a bit stuck - so any help would be appreciated
how do i loop through each row and assign it the random value i'm generating?
Here is my Storedproc:
CREATE PROCEDURE StoredProc8
AS
BEGIN
DECLARE #total INT
DECLARE #Count INT = 0
DECLARE #Random INT = 0
SELECT #total = COUNT(CustomerID) FROM Customers
WHILE(#Count<= #total)
BEGIN
SELECT #Random = 2 * RAND()
EXEC ('update Customers set col1= ' + #Random )
SELECT #Count = #Count+1
END
END
If you simple need to assign 0 or 1 randomly - you can use RAND() with random seed:
UPDATE Customers SET COL1 = RAND(CHECKSUM(NEWID()))*2
Demo: http://sqlfiddle.com/#!3/31699/9

Must declare a scalar variable

I was creating a column that will give a me random number but I was getting some errors.
CREATE TABLE tblBookInfo
(
AccessionNumber NVARCHAR(MAX)
RandomNumber NVARCHAR(10);
AccNo NVARCHAR(MAX)
#Upper INT;
#Lower INT
SET #Lower = 1
SET #Upper = 9999
Select #RandomNumber = Round (((#Upper - #Lower -1)* RAND() + #Lower), 0)
SET #AccNo = 'LIBBOOKS' + RandomNumber
SELECT #AccNo
Set AccessionNumber = AccNo
)
ERRORS:
Incorrect syntax near 'RandomNumber'.
Must declare the scalar variable "#Lower".
Must declare the scalar variable "#Upper".
Must declare the scalar variable "#Upper".
Must declare the scalar variable "#AccNo".
Must declare the scalar variable "#AccNo".
tHank you for your help :D
Its not very clear what you are trying to accomplish, but here is my interpretation of your code in the correct T-SQL syntax.
I'm not prepared to guess what you're trying to do below that.
CREATE TABLE tblBookInfo
(
AccessionNumber NVARCHAR(MAX),
RandomNumber NVARCHAR(10),
AccNo NVARCHAR(MAX)
)
DECLARE #Upper INT,
#Lower INT,
#RandomNumber INT
SET #Lower = 1 SET #Upper = 9999
SELECT #RandomNumber = Round (((#Upper - #Lower -1)* RAND() + #Lower), 0)
SELECT #RandomNumber

Number of times a particular character appears in a string

Is there MS SQL Server function that counts the number of times a particular character appears in a string?
There's no direct function for this, but you can do it with a replace:
declare #myvar varchar(20)
set #myvar = 'Hello World'
select len(#myvar) - len(replace(#myvar,'o',''))
Basically this tells you how many chars were removed, and therefore how many instances of it there were.
Extra:
The above can be extended to count the occurences of a multi-char string by dividing by the length of the string being searched for. For example:
declare #myvar varchar(max), #tocount varchar(20)
set #myvar = 'Hello World, Hello World'
set #tocount = 'lo'
select (len(#myvar) - len(replace(#myvar,#tocount,''))) / LEN(#tocount)
Look at the length of the string after replacing the sequence
declare #s varchar(10) = 'aabaacaa'
select len(#s) - len(replace(#s, 'a', ''))
>>6
You can do that using replace and len.
Count number of x characters in str:
len(str) - len(replace(str, 'x', ''))
Use this function begining from SQL SERVER 2016
Select Count(value) From STRING_SPLIT('AAA AAA AAA',' ');
-- Output : 3
When This function used with count function it gives you how many
character exists in string
try that :
declare #t nvarchar(max)
set #t='aaaa'
select len(#t)-len(replace(#t,'a',''))
You can do it inline, but you have to be careful with spaces in the column data. Better to use datalength()
SELECT
ColName,
DATALENGTH(ColName) -
DATALENGTH(REPLACE(Col, 'A', '')) AS NumberOfLetterA
FROM ColName;
-OR-
Do the replace with 2 characters
SELECT
ColName,
-LEN(ColName)
+LEN(REPLACE(Col, 'A', '><')) AS NumberOfLetterA
FROM ColName;
function for sql server:
CREATE function NTSGetCinC(#Cadena nvarchar(4000), #UnChar nvarchar(100))
Returns int
as
begin
declare #t1 int
declare #t2 int
declare #t3 int
set #t1 = len(#Cadena)
set #t2 = len(replace(#Cadena,#UnChar,''))
set #t3 = len(#UnChar)
return (#t1 - #t2) / #t3
end
Code for visual basic and others:
Public Function NTSCuentaChars(Texto As String, CharAContar As String) As Long
NTSCuentaChars = (Len(Texto) - Len(Replace(Texto, CharAContar, ""))) / Len(CharAContar)
End Function
It will count occurrences of a specific character
DECLARE #char NVARCHAR(50);
DECLARE #counter INT = 0;
DECLARE #i INT = 1;
DECLARE #search NVARCHAR(10) = 'o'
SET #char = N'Hello World';
WHILE #i <= LEN(#char)
BEGIN
IF SUBSTRING(#char, #i, 1) = #search
SET #counter += 1;
SET #i += 1;
END;
SELECT #counter;
Use this code, it is working perfectly.
I have create a sql function that accept two parameters, the first param is the long string that we want to search into it,and it can accept string length up to 1500 character(of course you can extend it or even change it to text datatype).
And the second parameter is the substring that we want to calculate the number of its occurance(its length is up to 200 character, of course you can change it to what your need). and the output is an integer, represent the number of frequency.....enjoy it.
CREATE FUNCTION [dbo].[GetSubstringCount]
(
#InputString nvarchar(1500),
#SubString NVARCHAR(200)
)
RETURNS int
AS
BEGIN
declare #K int , #StrLen int , #Count int , #SubStrLen int
set #SubStrLen = (select len(#SubString))
set #Count = 0
Set #k = 1
set #StrLen =(select len(#InputString))
While #K <= #StrLen
Begin
if ((select substring(#InputString, #K, #SubStrLen)) = #SubString)
begin
if ((select CHARINDEX(#SubString ,#InputString)) > 0)
begin
set #Count = #Count +1
end
end
Set #K=#k+1
end
return #Count
end

How to populate a database column with random numbers

How do I populate a int column, currently empty, with random numbers with no duplicates?
If this is an existing table to which you added a new INT column, you can do something like this:
UPDATE MyTable
SET MyIntColumn = CONVERT(int, RAND(CHECKSUM(NEWID())) * 10000);
This will populate the empty column with random numbers between 1 and 10000.
I suppose you could make the column a primary key to prevent duplicates, though that's kind of a hack. You can remove the key later.
---- Create the variables for the random number generation
DECLARE #Random INT;
DECLARE #Upper INT;
DECLARE #Lower INT;
DECLARE #Index integer
---- This will create a random number between 1 and 999
SET #Lower = 1 ---- The lowest random number
SET #Upper = 999 ---- The highest random number
SET #Index = 0 --- A while loop counter
--- Loop from 0 to 10
WHILE #Index < 10
BEGIN
SELECT 'loop counter = ', #index
SELECT #Random = ROUND(((#Upper - #Lower -1) * RAND() + #Lower), 0)
--Insert #Random here.
SET #index = #index + 1
END

Resources