//
you're reading...
SQL Server

T-SQL Random Date from Date Range

Here’s a quick bit of code that I find useful for generating test data for dates within a given date range. It uses a combination of the rand, newid, checksum, datediif and dateadd functions. First we calculate the checksum on a newid(). This generates a random integer value. Next we apply the rand function to the results and generate a random fraction which is applied to the datediff of your date range + 1. This results in a random number that represents the number of days to add to the start date.

dateadd(day, rand(checksum(newid()))*(1+datediff(day, ‘2011-01-01′,’2014-04-30’)), ‘2011-01-01’)

 

DECLARE @StartDate Datetime = ‘2011-01-01’                                                     DECLARE @EndDate Datetime = ‘2014-04-30’                                                           SELECT DATEADD(day,RAND(CHECKSUM(NEWID()))*(1+DATEDIFF(day, @StartDate,@EndDate)),@StartDate)                                    

Advertisements

About ldgaller

Accomplished Data Warehouse Architect, DBA and Software Architect with over 15 years of professional experience and demonstrated success designing and implementing solutions that improve business functionality and productivity. Highly diverse technical background with proven ability to design, develop and implement technology on an enterprise level. I approach all projects with passion, diligence, integrity, and exceptional aptitude.

Discussion

No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: