参数为@year,表示年份,然后自动返回当年所有的日期,格式为:
Date Week Note
--------------------------------------------
20080101 星期二 NULL
20080102 星期三 NULL
20080103 星期四 NULL
.... ...
20081228 星期日 NULL
20081229 星期一 NULL
20081230 星期二 NULL
20081231 星期三 NULL
use Test
Go
If Object_id('usp_Calendar') Is Not null
Drop proc usp_Calendar
Go
Create Proc usp_Calendar
(@year int)
As
Declare @Startdate datetime,
@EndDate datetime
If Isdate(Rtrim(@year)+'0101')=0
Return
Select @Startdate=Rtrim(@year)+'0101',
@EndDate=Rtrim(@year)+'1231'
;With
t0 As(Select id=1 Union All Select id=1),
t1 As(Select a.id From t0 a,t0 b),
t2 As(Select a.id From t1 a,t1 b),
t3 As(Select a.id From t2 a,t2 b),
t4 As(Select id=Row_number() Over(Order By a.id) From t3 a,t1 b)
Select
DATE=Convert(char(8),@Startdate+id-1,112),
WEEK=Datename(dw,@Startdate+id-1),
NOTE=null
From t4
Where id<=Datediff(day,@Startdate,@EndDate)+1
Go
Exec usp_Calendar 2008
Go
Go
If Object_id('usp_Calendar') Is Not null
Drop proc usp_Calendar
Go
Create Proc usp_Calendar
(@year int)
As
Declare @Startdate datetime,
@EndDate datetime
If Isdate(Rtrim(@year)+'0101')=0
Return
Select @Startdate=Rtrim(@year)+'0101',
@EndDate=Rtrim(@year)+'1231'
;With
t0 As(Select id=1 Union All Select id=1),
t1 As(Select a.id From t0 a,t0 b),
t2 As(Select a.id From t1 a,t1 b),
t3 As(Select a.id From t2 a,t2 b),
t4 As(Select id=Row_number() Over(Order By a.id) From t3 a,t1 b)
Select
DATE=Convert(char(8),@Startdate+id-1,112),
WEEK=Datename(dw,@Startdate+id-1),
NOTE=null
From t4
Where id<=Datediff(day,@Startdate,@EndDate)+1
Go
Exec usp_Calendar 2008
Go
另,考虑只是查询一年,使用递归的CTE:
use Test
Go
If Object_id('usp_Calendar') Is Not null
Drop proc usp_Calendar
Go
Create Proc usp_Calendar
(@year int)
As
Declare @Startdate datetime,
@EndDate datetime
If Isdate(Rtrim(@year)+'0101')=0
Return
Select @Startdate=Rtrim(@year)+'0101',
@EndDate=Rtrim(@year)+'1231'
;With
t As
(
Select id=Convert(int,0),Date=@Startdate,Week=Convert(nvarchar(20),@Startdate)
Union All
Select id=Convert(int,id+1),Date=Date+1,Week=Convert(nvarchar(20),Date+1)
From t Where Date<@EndDate
)
Select Date,Week,Note=null From t Option(Maxrecursion 0)
Go
Exec usp_Calendar 2008
Go
Go
If Object_id('usp_Calendar') Is Not null
Drop proc usp_Calendar
Go
Create Proc usp_Calendar
(@year int)
As
Declare @Startdate datetime,
@EndDate datetime
If Isdate(Rtrim(@year)+'0101')=0
Return
Select @Startdate=Rtrim(@year)+'0101',
@EndDate=Rtrim(@year)+'1231'
;With
t As
(
Select id=Convert(int,0),Date=@Startdate,Week=Convert(nvarchar(20),@Startdate)
Union All
Select id=Convert(int,id+1),Date=Date+1,Week=Convert(nvarchar(20),Date+1)
From t Where Date<@EndDate
)
Select Date,Week,Note=null From t Option(Maxrecursion 0)
Go
Exec usp_Calendar 2008
Go