declare @LASTMONTH date = '2018-10-01';
WITH MTHS AS (
SELECT dateadd(month,month(getdate()),dateadd(year,year(getdate()) - 1900, 0)) aday
UNION ALL
SELECT DATEADD(month,1,aday) from MTHS WHERE aday <= @LASTMONTH
),
LASTDAYS AS (SELECT DATEADD(day,-1,aday) finaldayofmonth from MTHS)
select * from LASTDAYS
這裏是前進或倒退適當
declare @LASTMONTH date = '2013-10-01';
WITH DIF AS (SELECT CASE WHEN
YEAR(@LASTMONTH) * 12 + MONTH(@LASTMONTH)
>= YEAR(GETDATE()) * 12 + MONTH(getdate()) THEN 1 ELSE -1 END x),
MTHS AS (
SELECT dateadd(month,month(getdate()),dateadd(year,year(getdate()) - 1900, 0)) aday
UNION ALL
SELECT DATEADD(month,(SELECT X from dif),aday) from MTHS
WHERE month(aday) != month(dateadd(month,1,@LASTMONTH)) or YEAR(aday) != YEAR(dateadd(month,1,@LASTMONTH))
),
LASTDAYS AS (SELECT DATEADD(day,-1,aday) finaldayofmonth from MTHS)
select * from LASTDAYS order by finaldayofmonth
你的答案是第一個,它的工作原理,但是我對上述如何成爲「遞歸」有點困惑?換句話說,實際的'循環/遞歸'如何/在哪裏發生? –
CTE定義中查詢的第二部分是遞歸發生的地方。 CTE中從CTE中選擇的部分:) –
謝謝你的解釋傑夫! –