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 expression are both char(100) for example
Any advices?
Asked
Active
Viewed 484 times
0
4 Answers
1
SET the @Length to what you need. Add more copies of sys.objects as necessary.
DECLARE @Length INT
SET @Length = 10000
DECLARE @RandomDigits VARCHAR(MAX)
SET @RandomDigits = ''
SELECT TOP (@Length) @RandomDigits = @RandomDigits + RIGHT(CHECKSUM(NEWID()), 1)
FROM sys.objects a, sys.objects b, sys.objects c
SELECT @RandomDigits

Muqo
- 414
- 7
- 15
0
To get a string of 100 random digits, concatenate output of CHECKSUM
over NEWID
function:
select substring(list, 1, 100)
from (
select c as [text()]
from (
select cast(abs(checksum(newid())) as varchar(max)) as c
from sys.objects
) x
for xml path('')
) x(list)

dean
- 9,960
- 2
- 25
- 26
0
One way is to use a recursive CTE:
with cte as (
select cast(right(checksum(newid()), 1) as varchar(8000)) as val, 1 as len
union all
select val + right(checksum(newid()), 1), len + 1
from cte
where len < 100
)
select *
from cte
where len = 100;

Gordon Linoff
- 1,242,037
- 58
- 646
- 786
0
if the number of digits is less or equals 10, you can just copy below code
DECLARE @digitsCount INT = 5;
SELECT RIGHT(CHECKSUM(NEWID()), @digitsCount)

kazem
- 3,671
- 1
- 22
- 21