Question : SQL Insert Given Date Range

I have a SQL table which has various columns, one of them is the date (date only) and the others are peoples movements for that date.

There are better ways of doing this I know, but this is the most straight forward one for the requirement I had, all I do is insert new movements for given people on a daily basis - and datestamping them with the applicable date

What I want to add now, is the next 1 years worth of dates automatically so that my SQL table will have 365 new rows, start with 04/01/2010 and incrementing 1 day at a time until it reaches a given date. (03/01/2011 in this case).

I know it can be done with 2 columns, one having start_date and another having end_date and SELECT WHERE BETWEEN but I don't want to change the existing structure of the table if possible as most people have their movements for each day.

Thanks in Advance

Answer : SQL Insert Given Date Range

What DB engine?  

If you are using SQL Server, this is a function that I use to generate dates.


To return 365 dates from a given date:

Example:
select * from [dbo].[fn_GetDateRange]('2010-01-04',0,365)
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
if object_id('[dbo].[fn_GetDateRange]') is not null
     drop function [dbo].[fn_GetDateRange]
go
create function [dbo].[fn_GetDateRange](@BaseDate datetime, @DaysBefore int, @DaysAfter int)
returns @Dates Table
   (theDate      datetime 
   )
as
/************************************************************
*
*    Author:        Brandon Galderisi
*    Last modified: 07-Oct-2008
*    Purpose:       Given a base date, returns a range of 
*                   dates from @DaysBefore before the @BaseDate
*                   to @DaysAfter the @BaseDate.
*    
*
*************************************************************/
begin
declare    @minDate datetime
set @minDate=dateadd(d,-@DaysBefore,@BaseDate)

;with
       cte0 as (select 1 as c union all select 1), 
       cte1 as (select 1 as c from cte0 a, cte0 b), 
       cte2 as (select 1 as c from cte1 a, cte1 b), 
       cte3 as (select 1 as c from cte2 a, cte2 b), 
       cte4 as (select 1 as c from cte3 a, cte3 b), 
       cte5 as (select 1 as c from cte4 a, cte4 b), 
       nums as (select row_number() over (order by c) as n from cte5)
insert into @Dates
select @MinDate
union
select dateadd(d,n,@MinDate) from nums 
where n<=@DaysBefore+@DaysAfter
order by 1


return
end
go
Random Solutions  
 
programming4us programming4us