SQL 生成日历


ALTER PROCEDURE [dbo].[ST_GetCalendar_S]
    @Year INT,
    @Month INT
AS
BEGIN
 DECLARE @Inmonth as varchar(7)
 SET @Inmonth =  CONVERT(VARCHAR,@Year)+'-'+ CONVERT(VARCHAR,@Month)
 
 DECLARE @a table(id int identity(0,1),date datetime)

 INSERT INTO @a(date)
 SELECT TOP 31 @Inmonth + '-01' FROM sysobjects
 UPDATE @a set date=dateadd(dd,id,date)
 
 select 日,一,二,三,四,五,六
 from
 (
  select week ,
   max(case weekday when 1 then datename(day,dt) else '' end ) '日',
   max(case weekday when 2 then datename(day,dt) else '' end ) '一',
   max(case weekday when 3 then datename(day,dt) else '' end ) '二',
   max(case weekday when 4 then datename(day,dt) else '' end ) '三',
   max(case weekday when 5 then datename(day,dt) else '' end ) '四',
   max(case weekday when 6 then datename(day,dt) else '' end ) '五',
   max(case weekday when 7 then datename(day,dt) else '' end ) '六'
  from
  (
   select week = datepart(week , m.dt) , weekday = datepart(weekday , m.dt) , dt from
   (
    select dt = date
    FROM @a
    where date < dateadd(month , 1 , @Inmonth + '-01')
   ) m
  ) n
  group by week
 ) o    
 
END

posted @ 2011-08-03 01:16  星火卓越  阅读(256)  评论(0编辑  收藏  举报