Press "Enter" to skip to content

Generate random data

The following is a quick & easy way to generate some random data in a temp table. It’s not very complex but it can be useful for quick testing purposes.

Notes:

  • NEWID creates a UniqueIdentifier datatype with a length of 36 characters (including hyphens).
  • GO x (where x is an integer) will execute the batch x times.
DROP TABLE IF EXISTS #temp;

CREATE TABLE #temp (
    [RandomNumber] TINYINT
    ,[RandomPastDate] DATE
    ,[RandomFutureDate] DATE
    ,[RandomTime] TIME
    ,[RandomDateTime] DATETIME
    ,[RandomString1] CHAR(10)
    ,[RandomString2] CHAR(40)
);
GO

INSERT INTO #temp (
    [RandomNumber]
    ,[RandomPastDate]
    ,[RandomFutureDate]
    ,[RandomTime]
    ,[RandomDateTime]
    ,[RandomString1]
    ,[RandomString2]
)
SELECT [RandomNumber] = CAST(RAND() * 100 AS TINYINT)
    ,[RandomPastDate] = DATEADD(DAY, CAST(RAND() * -365 AS INT), GETUTCDATE())
    ,[RandomFutureDate] = DATEADD(DAY, CAST(RAND() * 365 AS INT), GETUTCDATE())
    ,[RandomTime] = DATEADD(MINUTE, CAST(RAND() * 3600 AS INT), GETUTCDATE())
    ,[RandomDateTime] = DATEADD(DAY, CAST(RAND() * 365 AS INT),
        DATEADD(MINUTE, CAST(RAND() * 3600 AS INT), GETUTCDATE())
    )
    ,[RandomString1] = CAST(REPLACE(NEWID(), '-', '') AS CHAR(10))
    ,[RandomString2] = CAST(REPLACE(NEWID(), '-', '') AS CHAR(20))
        + CAST(REPLACE(NEWID(), '-', '') AS CHAR(20)
);

GO 10 -- execute the batch 10 times

SELECT * FROM #temp;

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *