how to get current month full days in sql server?

Farshad Valizade 501 Reputation points
2023-12-07T04:23:29.0466667+00:00

Hi guys.

I want to get current date from system and return 30-31 days of current month

foreaxmple : today is 12/7/2023

query should return :

12/01/2023

12/02/2023

...

12/30/2023

and show 30 days for 30days month 29 for 29 month and ...

SQL Server Other
0 comments No comments
{count} votes

Accepted answer
  1. LiHongMSFT-4306 31,566 Reputation points
    2023-12-07T05:43:52.1466667+00:00

    Hi @Farshad Valizade

    Try this query:

    ;WITH DateTable AS
    (
     SELECT  DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0) AS [date] 
     UNION ALL
     SELECT DATEADD(DAY, 1, [date])
     FROM DateTable
     WHERE DATEADD(DAY, 1, [date]) <= EOMONTH(GETDATE())
    )
     SELECT CAST([date] AS date) DaysOfMonth
     FROM DateTable 
    

    Best regards,

    Cosmog Hong


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


1 additional answer

Sort by: Most helpful
  1. LiHongMSFT-4306 31,566 Reputation points
    2023-12-07T06:27:07.5866667+00:00

    Hi @Farshad Valizade

    If SQL Server 2017+ then use STRING_AGG like this:

    ;WITH DateTable AS
    (
     SELECT  DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0) AS [date] 
     UNION ALL
     SELECT DATEADD(DAY, 1, [date])
     FROM DateTable
     WHERE DATEADD(DAY, 1, [date]) <= EOMONTH(GETDATE())
    )
    SELECT STRING_AGG(CAST([date] AS date), ' | ') WITHIN GROUP (ORDER BY [date] ASC) AS DaysOfMonth
    FROM DateTable
    

    If versions before 2017, check this query:

    ;WITH DateTable AS
    (
     SELECT  DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0) AS [date] 
     UNION ALL
     SELECT DATEADD(DAY, 1, [date])
     FROM DateTable
     WHERE DATEADD(DAY, 1, [date]) <= EOMONTH(GETDATE())
    )
    SELECT STUFF((SELECT ' | ' + CONVERT(CHAR(10),[date],111) FROM DateTable ORDER BY [date]
                  FOR XML PATH('')),1,2,'') AS DaysOfMonth
    
    1 person found this answer helpful.

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.