Get first Sunday of next month using T-SQL

后端 未结 9 2109
梦毁少年i
梦毁少年i 2021-02-09 13:19

Looking for a way to get the date in the format \"11/1/2009\", which would be the first sunday of next month. I want to run this query after the first sunday in october to get

9条回答
  •  不思量自难忘°
    2021-02-09 13:45

    Reference taken from this blog:

    SQL Server 2012 introduced one new TSQL EOMONTH to return the last day of the month that contains the specified date with an optional offset.

    CREATE TABLE tbl_Test_EOMONTH
    (
        SampleDate DATETIME
    )
    GO
    
    INSERT INTO tbl_Test_EOMONTH VALUES ('2015-12-20')
    INSERT INTO tbl_Test_EOMONTH VALUES ('2015-11-08')
    INSERT INTO tbl_Test_EOMONTH VALUES ('2015-10-16')
    INSERT INTO tbl_Test_EOMONTH VALUES ('2015-09-26')
    INSERT INTO tbl_Test_EOMONTH VALUES ('2016-01-31') 
    GO
    
    SELECT 
        DATEADD(DAY,8-DATEPART(WEEKDAY,DATEADD(DAY,0,EOMONTH([SampleDate])))
        ,EOMONTH([SampleDate])) AS FirstSunday_ofTheNextMonth
    FROM tbl_Test_EOMONTH
    GO
    

提交回复
热议问题