Skip to content

Instantly share code, notes, and snippets.

@clxy
Last active April 13, 2020 10:22
Show Gist options
  • Save clxy/52fdcfe2ab9406dfa49a27bbe4f478b0 to your computer and use it in GitHub Desktop.
Save clxy/52fdcfe2ab9406dfa49a27bbe4f478b0 to your computer and use it in GitHub Desktop.
MS SQL Server - create list of month by with clause. @see https://stackoverflow.com/a/9255298
---
-- Personally, I liked this one!
---
declare @ym_to date = cast('20190401' as date);
declare @ym_from date = cast('20181201' as date);
with months(dt) as (
select @ym_to dt
union all
select dateadd(month, -1, dt) from months
)
select
top (datediff(month, @ym_from, @ym_to) + 1)
format(months.dt, 'yyyyMM') ym
from months
option (maxrecursion 13);
declare @ym_to date = cast('20190401' as date);
declare @ym_from date = cast('20181201' as date);
with
months as (
--==== creates a "tally table" structure for months to add to start date
-- calulated by the difference in months between the start and end date.
-- then adds those numbers to the start of the month of the start date.
select
top (datediff(month, @ym_from, @ym_to) + 1)
dt = dateadd(month, datediff(month, 0, @ym_from) + (row_number() over (order by (select null)) -1), 0)
from sys.all_columns ac1
cross join sys.all_columns ac2
)
--===== slice each "whole month" date into the desired display values.
select format(months.dt, 'yyyyMM') ym
from months;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment