Get first Sunday of next month using T-SQL

后端 未结 9 2099
梦毁少年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 14:03

    This would be simplest with an auxiliary calendar table. See this link, for example.

    However, it can be done without one, though it's rather tricky. Here I assume you want the first future date that is the first Sunday of a month. I've written this with a variable @now for - well - now, so it's easier to test. It might be possible to write more simply, but I think this has a better chance of being correct than quickly-written simpler solutions. [Corrected by adding DAY(d) < 8]

    SET @now = GETDATE();
    WITH Seven(i) AS (
      SELECT -1 UNION ALL SELECT 0 UNION ALL SELECT 1
                UNION ALL SELECT 3 UNION ALL SELECT 4
                UNION ALL SELECT 5 UNION ALL SELECT 6
    ), Candidates(d) AS (
      SELECT DATEADD(WEEK,i+DATEDIFF(WEEK,'19000107',@now),'19000107')
      FROM Seven
    ) 
      SELECT TOP (1) d AS SoonestFutureFirstSunday
      FROM Candidates
      WHERE DAY(d) < 8 AND MONTH(d) >= MONTH(@now)
      AND (MONTH(d) > MONTH(@now) OR DAY(d) > DAY(@now)) 
      ORDER BY d;      ORDER BY d;
    

提交回复
热议问题