SQL Server How to display the last day of month instead of first in SQL query recursion

xn1cxnb4  于 2023-11-16  发布在  其他
关注(0)|答案(2)|浏览(118)

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.

wz3gfoph

wz3gfoph1#

I went with a simpler solution:

Update the SELECT DateData to SELECT EOMONTH(DateData) and that solved the issue.

Thank you everyone for the help.

mkshixfv

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.

DECLARE @StartDateTime DATETIME
DECLARE @EndDateTime DATETIME
 
SET @StartDateTime = '2015-01-01'
SET @EndDateTime = '2016-01-12';
 
WITH DateRange AS 
(
    SELECT EOMONTH(@StartDateTime) as DateData, @StartDateTime AS StartOfMonth
    UNION ALL
    SELECT EOMONOTH(DATEADD(m, 1, StartOfMonth))
    FROM DateRange 
    WHERE DateData < @EndDateTime
)
SELECT DateData
FROM DateRange
OPTION (MAXRECURSION 0)

Recursion is slow. GENERATE_SERIES or some other numbers generator is probably better. EOMONTH also provides an increment parameter, which means you don't need DATEADD

DECLARE @StartDateTime DATETIME
DECLARE @EndDateTime DATETIME
 
SET @StartDateTime = '2015-01-01'
SET @EndDateTime = '2016-01-12';
 
SELECT
  EOMONTH(@StartDateTime, g.value) AS DateData
FROM GENERATE_SERIES(0, DATEDIFF(month, @StartDateTime, @EndDateTime)) g;

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) .

相关问题