Generate Random Dates
Saturday, December 15, 2012
by jsalvo
I was preparing a demo for a presentation and needed to generate some random dates within a specified timeframe. I came across the following SQL that worked well for demo purposes and am recording it on my blog since it may prove to be useful in the future.
@MaxDate is the maximum date the script can generate and @YearsPrior is the number of years prior to the maximum date.
For example, if you need to generate random birthdates, set @MaxDate to the current day and @YearsPrior to 90.
DATEADD(day, DATEDIFF(day, 0, @MaxDate) – 1 – FLOOR(RAND(CAST(NEWID() AS Binary(4))) * 365.24 * @YearsPrior), 0)
Comments
comments powered by Disqus