Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

query for first and last day of month

Tags:

sql

sql-server

If I have the name of the month, how can I have the first and last day of that month in SQL?

I have this query to returns the month names:

DECLARE @StartDate  DATETIME,
        @EndDate    DATETIME;

SELECT   @StartDate = '20110501'        
        ,@EndDate   = '20110801';


SELECT  DATENAME(MONTH, DATEADD(MONTH, x.number, @StartDate)) AS MonthName
FROM    master.dbo.spt_values x
WHERE   x.type = 'P'        
AND     x.number <= DATEDIFF(MONTH, @StartDate, @EndDate)

Result:

results

Now, how can i get the first and last day of that months? changing the query.

like image 424
PookPook Avatar asked Sep 03 '25 06:09

PookPook


1 Answers

If you want a more general and simple solution:

DECLARE @startdate AS DATETIME = GETDATE()
SELECT      
DATEADD(MONTH, DATEDIFF(MONTH, 0, @startdate) , 0)   as startMonth,
DATEADD(SECOND, -1, DATEADD(MONTH, 1,  DATEADD(MONTH, DATEDIFF(MONTH, 0, @startdate) , 0) ) ) as endMonthExactly,
EOMONTH(@startdate) as endMonthDay

Gives the result:

startMonth       2023-12-01 00:00:00
endMonthExactly  2023-12-31 23:59:59
endMonthDay      2023-12-31
like image 95
Sire Avatar answered Sep 04 '25 22:09

Sire