Skip to content

[SQL SERVER] – GENERATE RANDOM DATETIME WITHIN A RANGE

One of these days I had the need to obtain a random datetime inside a specified range, on SQL Server 2008+.

After a few minutes I came up with this script:

DECLARE @DateFrom DATETime = '2012-01-01'
DECLARE @DateTo DATETIME = '2012-06-30'
DECLARE @DaysRandom Int= 0
DECLARE @MillisRandom Int=0
 
--get random number of days
 
select @DaysRandom= DATEDIFF(day,@DateFrom,@DateTo)
SELECT @DaysRandom = ROUND(((@DaysRandom -1) * RAND()), 0)
 
--get random millis
SELECT @MillisRandom = ROUND(((99999999) * RAND()), 0)
 
SELECT @DateTo = DATEADD(day, @DaysRandom, @DateFrom)
SELECT @DateTo = DATEADD(MILLISECOND, @MillisRandom, @DateTo)
SELECT @DateTo

Hope it’s useful.

Published inDatabases

Be First to Comment

Leave a Reply