How can I select a random date within a specific inclusive range, let's say '1950-01-01' and '1999-12-31' with SQL Server?
select DateAdd(d, ROUND(DateDiff(d, '1950-01-01', '1999-12-31') * RAND(), 0), '1950-01-01')
EDIT
If this is to be executed as part of a statement that returns multiple rows or as part of update, the RAND() would return single value for the whole resultset. For that case RAND(CHECKSUM(NEWID())) can be used.
select DateAdd(d, ROUND(DateDiff(d, '1950-01-01', '1999-12-31') * RAND(), 0), '1950-01-01'),
DateAdd(d, ROUND(DateDiff(d, '1950-01-01', '1999-12-31') * RAND(CHECKSUM(NEWID())), 0), '1950-01-01')
from master..spt_values where type = 'P'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With