Skip to content
Advertisement

How do I use a variable to create a randomized date for every row in a column?

I’m currently trying to randomize every date inside a column!

Will this create a single random date for the variable and assign it to every row, or will this generate a unique randomized date for every row?

DECLARE @RandomDate DATETIME
SET @RandomDate = CONVERT(varchar,DATEADD(DAY, ABS(CHECKSUM(NEWID()) % (364 * 5), '2000-01-01', 121)

UPDATE myDateTable
SET randomDateColumn = @RandomDate

(I’m using a variable here instead of just doing it right in the update statement because I also have another column that I’m adding a randomized number of days after the variable’s date!)

Advertisement

Answer

The variable is set before the statement is executed; its value is then assigned to the whole column.

If you want a random value on each row, then you need to put the expression inside the query:

UPDATE myDateTable
SET randomDateColumn = DATEADD(DAY, ABS(CHECKSUM(NEWID()) % (364 * 5), '2000-01-01')
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement