Database Journal
MS SQL Oracle DB2 Access MySQL PostgreSQL Sybase PHP SQL Etc SQL Scripts & Samples Links Database Forum

» Database Journal Home
» Database Articles
» Database Tutorials
MS SQL
Oracle
DB2
MS Access
MySQL
» RESOURCES
Database Tools
SQL Scripts & Samples
Links
» Database Forum
» Sitemap
Free Newsletters:
DatabaseDaily  
News Via RSS Feed


follow us on Twitter
Database Journal |DBA Support |SQLCourse |SQLCourse2
 

Featured Database Articles

SQL Scripts & Samples

Posted Mar 11, 2005

Calendar

By DatabaseJournal.com Staff



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



SQL Scripts & Samples Archives

Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 




Latest Forum Threads
SQL Scripts & Samples Forum
Topic By Replies Updated
sql help!! add 1 August 22nd, 11:58 AM
How To Combine These 2 Queries into 1 Query ? tarek_land 1 June 7th, 08:37 AM
solving query svibuk 1 February 3rd, 06:08 AM
converting from a character string to uniqueidentifier saturnius 4 January 4th, 05:56 AM


















Thanks for your registration, follow us on our social networks to keep up-to-date