S.Das S.Das - 1 year ago 67
SQL Question

SQL query to get list of months till now by entering year

I have a requirement where I have to display all the months of present year till now when year parameter is entered.

For example if I enter 2016, then all months till September should be shown.

How to achieve this? Any ideas would be highly appreciated.

Answer Source

Use the below script.

;with months (date)
    SELECT cast(@year+'-01-01' as date)
    SELECT DATEADD(month,1,date)
    from months
    where  DATEADD(month,1,date)<= case when @year=YEAR(getdate()) THEN CAST(getdate() as date) ELSE cast(@year+'-12-31' as date) END
select Datename(month,date) [Month] from months

Output :

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download