Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to dynamically populate table with date range?? 1

Status
Not open for further replies.

HiBoo

Programmer
Jan 11, 2000
88
CA
I need to dynamically populate a table with a date range given two date variables. Any ideas on how this can be done???

I would like to create a stored procedure that accepts two date parameters. The first parameter is 'FromDate', and the second parameter is 'ToDate'. I'd like to start by truncating the destination table. Then, starting with the 'FromDate' variable, insert that value into the table. Then I want to add one day to the 'FromDate' variable and insert that value into the table, etc, etc, etc... until the 'FromDate' equals the 'ToDate'. The table has only one field, 'TheDate'.

Example:
EXEC sp_CreateDateRange '01/01/2003', '01/05/2003'
GO
SELECT * FROM theTable

Result:
TheDate
01/01/2003
01/02/2003
01/03/2003
01/04/2003
01/05/2003

(5 row(s) affected)

I know how to truncate a table and increment the date. What I'm stuck on is the loop structure. Any thoughts???
 
So we are talking T-sql and not ANSI SQL.

create procedure (@startDate datetime, @endDate datetime)
as
declare @somedate dateTime
set @somedate = @startDate
while @somedate <= @enddate
begin
insert into theTable values(@someDate)
set @somedate = dateadd(day,1,@somedate)
end
 
Thanks swampBoogie, that is exactly what I needed and it works great.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top