How to Insert N Random Dates between a given range into a SQL Server Table

To insert N (@n) random dates between a given range (between @start and @end) into SQL Server Table use following T-SQL code:

DECLARE @start AS date
SET @start = '20130601'
DECLARE @end AS date
SET @end = '20130630'
DECLARE @range AS int
SET @range = DATEDIFF(dd, @start, @end) + 1
DECLARE @n AS int
SET @n = 1000

BEGIN TRANSACTION
DECLARE @uid uniqueidentifier
SET @uid = NEWID()
DECLARE @i AS int
SET @i = 1
WHILE(@i <= @n) BEGIN INSERT INTO Table_Name VALUES(DATEADD (dd, CEILING(RAND(CHECKSUM(@uid))*@range) - 1, @start)) SET @i += 1 SET @uid = NEWID() END COMMIT TRANSACTION

The table was populated with 1000 random dates between '20130601' and '20130630':

n_random_dates_between_given_range

To see how to insert N random integer numbers into a SQL Server Table, read related blog post:
Generating random numbers in SQL Server

If the post helped you, please share it:
Pin It

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">