Tuesday, August 21, 2012

SQL Server: Get First and Last Days Of Month

DECLARE @min DATETIME
DECLARE @max DATETIME
DECLARE @now DATETIME

SET @now = GETDATE();

--get first day of last month:
SET @min = CONVERT(VARCHAR(25),DATEADD(dd
,-(DAY(DATEADD(mm,1,@now))-1),DATEADD(mm,-1,@now)),101) 

--get the last day of last month
SET @max = CONVERT(VARCHAR(25),DATEADD(dd
,-(DAY(@now)),@now),101) 

--get the first day of current month
SET @min = CONVERT(VARCHAR(25),DATEADD(dd
,-(DAY(@now)-1),@now),101)  

--get the last day of current month
SET @max = CONVERT(VARCHAR(25),DATEADD(dd
,-(DAY(DATEADD(mm,1,@now))),DATEADD(mm,1,@now)),101) 

No comments:

Post a Comment