How To Generate Random Dates Between Two Date Range in SQL Server

Those who wants to generate random dates between two date ranges in SQL Server can use the following query:

DECLARE @FromDate DATETIME = DATEADD(DAY, -2, '2011-01-01')
DECLARE @ToDate   DATETIME = DATEADD(DAY, -1, '2017-01-01')


DECLARE @Seconds INT = DATEDIFF(SECOND, @FromDate, @ToDate)
DECLARE @Random INT = ROUND(((@Seconds-1) * RAND()), 0)
DECLARE @Milliseconds INT = ROUND((999 * RAND()), 0)

SELECT DATEADD(MILLISECOND, @Milliseconds, DATEADD(SECOND, @Random, @FromDate))


Hope it works for you!

Comments

Popular posts from this blog

The Power of .NET Core Caching: Best Practices for Optimal Performance

Custom Function string_split for SQL Server 2008R2 (T-SQL split string)

Find the number of columns in a table