Create Random String Of Digits T-sql
I need to create a string of random digits in TSQL I thought about HASH + CONVERT But convert works on style - so I am not show how can I do it if data type of result and expressio
Solution 1:
SET the @Length to what you need. Add more copies of sys.objects as necessary.
DECLARE@LengthINTSET@Length=10000DECLARE@RandomDigitsVARCHAR(MAX)
SET@RandomDigits=''SELECT TOP (@Length) @RandomDigits=@RandomDigits+RIGHT(CHECKSUM(NEWID()), 1)
FROM sys.objects a, sys.objects b, sys.objects c
SELECT@RandomDigitsSolution 2:
To get a string of 100 random digits, concatenate output of CHECKSUM over NEWID function:
selectsubstring(list, 1, 100)
from (
select c as [text()]
from (
selectcast(abs(checksum(newid())) asvarchar(max)) as c
from sys.objects
) x
for xml path('')
) x(list)
Solution 3:
One way is to use a recursive CTE:
with cte as (
selectcast(right(checksum(newid()), 1) asvarchar(8000)) as val, 1as len
unionallselect val +right(checksum(newid()), 1), len +1from cte
where len <100
)
select*from cte
where len =100;
Solution 4:
if the number of digits is less or equals 10, you can just copy below code
DECLARE@digitsCountINT=5;
SELECTRIGHT(CHECKSUM(NEWID()), @digitsCount)
Post a Comment for "Create Random String Of Digits T-sql"