Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeffjohnson9046/11204a5f662315aef6f0 to your computer and use it in GitHub Desktop.
Save jeffjohnson9046/11204a5f662315aef6f0 to your computer and use it in GitHub Desktop.
MSSQL - Generate a random datetime value for a given year.
DECLARE @RandomDate datetime
SELECT @RandomDate =
DATEADD(day, ROUND(DATEDIFF(day, '2015-01-01', '2015-12-31') * RAND(CHECKSUM(NEWID())), 0),
DATEADD(second, CHECKSUM(NEWID()) % 48000, '2015-01-01'))
/* Verify */
SELECT RandomDate = @RandomDate
@Garchibulin
Copy link

Genius! Thank you

@Divyanshi99-gilch
Copy link

DECLARE @start DATE = '2021-01-01'
DECLARE @EnD DATE = '2021-01-31'

SELECT DATEADD(DAY,ABS(CHECKSUM(NEWID())) % ( 1 + DATEDIFF(DAY,@start,@EnD)),@start)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment