Calendar

>>Script Language and Platform: T-SQL/MS SQL Server
This script returns calendar rows for month/year passed in.


select * from calendar(datetime)

example: select * from calendar(”3/1/2005”)
returns:
SUN MON TUE WED THU FRI SAT
—- —- —- —- —- —- —-
NULL NULL 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 NULL NULL

(5 row(s) affected)

Author: S. Hafthor



CREATE function calendar(@dt datetime)
returns @cal table(SUN tinyint,MON tinyint,TUE tinyint,WED tinyint,THU
tinyint,FRI tinyint,SAT tinyint)
as
begin
— declare @dt datetime set @dt=getdate()
set @dt=@dt+1-day(@dt) — first day of the month
set @dt=@dt+7-datepart(weekday,@dt) — first Saturday of the month
insert into @cal
select
case when month(@dt+wk+1)=month(@dt) then day(@dt+wk+1) end,
case when month(@dt+wk+2)=month(@dt) then day(@dt+wk+2) end,
case when month(@dt+wk+3)=month(@dt) then day(@dt+wk+3) end,
case when month(@dt+wk+4)=month(@dt) then day(@dt+wk+4) end,
case when month(@dt+wk+5)=month(@dt) then day(@dt+wk+5) end,
case when month(@dt+wk+6)=month(@dt) then day(@dt+wk+6) end,
case when month(@dt+wk+7)=month(@dt) then day(@dt+wk+7) end
from (
select -7 as wk union select 0 union select 7 union select 14 union
select 21 union select 28
) j
where month(@dt) in (month(@dt+wk+7),month(@dt+wk+1))
return
en



Disclaimer:
We hope that the information on these script pages is
valuable to you. Your use of the information contained in these pages,
however, is at your sole risk. All information on these pages is provided
“as -is”, without any warranty, whether express or implied, of its accuracy,
completeness, or fitness for a particular purpose…

Disclaimer Continued

Back to Database Journal Home

Get the Free Newsletter!

Subscribe to Cloud Insider for top news, trends & analysis

Latest Articles