SQL Function for Date Sequences (Version 2.1)
I believe this is the last version for date sequences function. Thanks to Enigma for some wise ideas (sorry, Enigma that I don't know your name). Thanks anyway. I added my 2 cents also.
So, you'd better see the final result - t-sql user defined function that generates date sequences:
/*
########################################################
#
# F_TBL_CALENDAR
#
# version # 2.1
#
# use: select * from dbo.F_TBL_CALENDAR(2004)
#
########################################################
*/
alter function F_TBL_CALENDAR
(@p_year smallint)
returns @tbl table (cal_date smalldatetime)
as
begin
-- 1 --
-- get start date
declare @p_start_date smalldatetime
select @p_start_date = convert(smalldatetime,
convert(varchar(4), @p_year)
+ '0101')
-- 2 --
-- calculate days in the year
declare @p_count int
select @p_count = datediff(dd, @p_start_date,
dateadd(yy, 1, @p_start_date))
-- 3 --
-- generate dates
insert into @tbl
select cal_date
from
(
select
@p_start_date +
n3.num * 100 +
n2.num * 10 +
n1.num as cal_date
from
(
select 0 as num union all
select 1 union all
select 2 union all
select 3 union all
select 4 union all
select 5 union all
select 6 union all
select 7 union all
select 8 union all
select 9
) n1,
(
select 0 as num union all
select 1 union all
select 2 union all
select 3 union all
select 4 union all
select 5 union all
select 6 union all
select 7 union all
select 8 union all
select 9
) n2,
(
select 0 as num union all
select 1 union all
select 2 union all
select 3
) n3
where (n3.num * 100 + n2.num * 10 + n1.num) < @p_count
) gencalendar
return
end
Enjoy
Thursday, April 15, 2004 2:43 AM