如何根据输入的年份获取所有月份,直到三月
假设:-如果年份是2018年,那么我只需要获取从10月(本月的下个月)到4月的所有月份。
因为这些值我需要传递给sp以获取表数据 如果这一年是2017年,那么我需要所有的几个月。 请帮助我
答案 0 :(得分:0)
可能会在下面的查询中为您提供帮助。
DECLARE @StartDateTime DATETIME
DECLARE @EndDateTime DATETIME
DECLARE @Year int= 2018 --Finanical year
SET @StartDateTime = CAST(CAST(@Year AS VARCHAR(20))+'-04-01' as datetime)
SET @EndDateTime = CAST(CAST(@Year+1 AS VARCHAR(20))+'-03-31' as datetime)
;WITH DateRange(Dates) AS
(
SELECT @StartDateTime as Date
Union ALL
SELECT DATEADD(d,1,Dates)
FROM DateRange
WHERE Dates < @EndDateTime
)
Select distinct DateName( month , DateAdd( month , month(dates) , 0 ) - 1 ) as monthname
,year(dates) as year
, month(dates) as monthnumber
from DateRange
where
(Year(GETDATE())=@Year AND DATEADD(m, DATEDIFF(m, -1, getdate()), 0)<dates)
OR
(Year(GETDATE())<>@Year )
order by year(dates), month(dates)
OPTION (MAXRECURSION 0)