Calendar | Database Journal

Calendar

Mar 11, 2005
1 minute read

>>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
begindeclare @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

Database Journal Logo

DatabaseJournal.com publishes relevant, up-to-date and pragmatic articles on the use of database hardware and management tools and serves as a forum for professional knowledge about proprietary, open source and cloud-based databases--foundational technology for all IT systems. We publish insightful articles about new products, best practices and trends; readers help each other out on various database questions and problems. Database management systems (DBMS) and database security processes are also key areas of focus at DatabaseJournal.com.

Property of TechnologyAdvice. © 2026 TechnologyAdvice. All Rights Reserved

Advertiser Disclosure: Some of the products that appear on this site are from companies from which TechnologyAdvice receives compensation. This compensation may impact how and where products appear on this site including, for example, the order in which they appear. TechnologyAdvice does not include all companies or all types of products available in the marketplace.