0

I need to insert random data in my database for testing, and would need to generate a numeric string (can start with 0) 27 characters long.

I've been looking into NEWID() but it contains also letters, same for NEWSEQUENTIALID().

So far my approach would be to make a while loop, generate each digit randomly and concatenate it, but it seems to be a very slow approach.

I am using MSSQL 2014.

4
  • Does this answer your question? Commented Nov 19, 2021 at 6:54
  • @Zhorov, no because it generates a single small integer that is up to 2 characters long. not 27. Commented Nov 19, 2021 at 6:59
  • select it from a TALLY table with the required number of digits and STRING_AGG() it Commented Nov 19, 2021 at 7:03
  • 1
    I'll offer this, but not as an answer, since then I'd be required to explain and defend it -- select right(replicate('0', 27) + convert(decimal(38, 0), 0x26000001 + crypt_gen_random(13)), 27). This approach cannot generate arbitrarily long values, but it's likely to be faster than anything else (where such things matter). Commented Nov 19, 2021 at 8:05

2 Answers 2

3

A possible solution, based on this approach (using CHECKSUM() and NEWID()):

CREATE TABLE TestTable(RandomNumber varchar(27))
DECLARE @length int = 27

;WITH rCTE AS (
   SELECT 1 AS n 
   UNION ALL 
   SELECT n + 1 
   FROM rCTE 
   WHERE n < @length
)
INSERT INTO TestTable(RandomNumber)
VALUES ((SELECT ABS(CHECKSUM(NEWID())) % 10 FROM rCTE FOR XML PATH('')))
-- For SQL Server 2017+
-- VALUES ((SELECT STRING_AGG(ABS(CHECKSUM(NEWID())) % 10, '') FROM rCTE))
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, unfortunately I am on MsSql 2014 and that does not have the STRING_AGG function. I add this information to the post
thank you, but how can I add this result to a insert statement? I tried but got the message that FOR XML is not allowed in an insert statement.
0

I'm using presto and and I found this solution:

SELECT LPAD(CAST(RANDOM(1000000000) AS VARCHAR), 27, '0')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.