Select a random date within specific range

前端 未结 2 602
不知归路
不知归路 2021-02-03 11:58

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?

2条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-03 12:18

    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'
    

提交回复
热议问题