SQL取得年月

SQL取得年月

DECLARE @StartDate DATE = '2022-11-01'; -- 你的開始日期
DECLARE @EndDate DATE = '2023-04-30'; -- 你的結束日期

WITH DateList AS (
   SELECT TOP (DATEDIFF(MONTH, @StartDate, @EndDate) + 1)
       YearNumber = YEAR(DATEADD(MONTH, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) - 1, @StartDate)),
       MonthNumber = MONTH(DATEADD(MONTH, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) - 1, @StartDate))
   FROM master.dbo.spt_values
)

select * from DateList