Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select a random date within specific range

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?

like image 568
Nicola Cossu Avatar asked Apr 01 '11 22:04

Nicola Cossu


1 Answers

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'
like image 77
amit_g Avatar answered Oct 27 '22 20:10

amit_g