• 根据年,自动生成日期



    参数为@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


    另,考虑只是查询一年,使用递归的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 
    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





  • 相关阅读:
    Codeforces Round #720 (Div. 2) B. Nastia and a Good Array(被坑好几次)1300
    B. Lord of the Values 思维数学建构 附加 英文翻译
    几个i的幂的累加公式1^2+2^2+3^2 2~5
    Codeforces Round #721 (Div. 2)A. And Then There Were K(位运算,二进制) B1. Palindrome Game (easy version)(博弈论)
    洛谷 P2392 kkksc03考前临时抱佛脚, dp / 深搜
    Codeforces Round #719 (Div. 3) C. Not Adjacent Matrix
    Educational Codeforces Round 108 (Div. 2), C map套vector存储
    Day39---->MySQL系列
    Day38——>MySQL
    Day37
  • 原文地址:https://www.cnblogs.com/wghao/p/1212518.html
Copyright © 2020-2023  润新知