I have the following query:
DECLARE @StartDateTime DATETIME
DECLARE @EndDateTime DATETIME
SET @StartDateTime = '2015-01-01'
SET @EndDateTime = '2016-01-12';
WITH DateRange(DateData) AS
(
SELECT @StartDateTime as Date
UNION ALL
SELECT DATEADD(m,1,DateData)
FROM DateRange
WHERE DateData < @EndDateTime
)
SELECT DateData
FROM DateRange
OPTION (MAXRECURSION 0)
It displays the first of the month in this format: yyyy-mm-dd hh:mm:ss:mmm
How can I update the query above so it displays:
- The last day of each month in the range
- In this format:
MM-dd-yyyy
Thanks.
2条答案
按热度按时间wz3gfoph1#
I went with a simpler solution:
Update the
SELECT DateData
toSELECT EOMONTH(DateData)
and that solved the issue.Thank you everyone for the help.
mkshixfv2#
You can use the
EOMONTH
function. Note that you should still increment off the first day in the month, otherwise you can run into issues.Recursion is slow.
GENERATE_SERIES
or some other numbers generator is probably better.EOMONTH
also provides an increment parameter, which means you don't needDATEADD
The format should not be relevant, that is purely a display/presentation thing. But if you really needed to stringify the date, you can use
CONVERT(varchar(10), yourDate, 110)
.