Friday, March 12, 2010

Beginning and End of Month in SQL Server

There are times my procedures process data on a monthly basis. The following script makes sure that the procedure processes data for last month on the 1st day of a month.

declare @sdate smalldatetime, @edate smalldatetime

-- @sdate and @edate mark the BOM and EOM
if @sdate is null
begin
    select @sdate = dateadd(day, -1, convert(smalldatetime, convert(char(8), getdate(), 1)))
    select @edate = dateadd(day, 1, @sdate)
    select @sdate = dateadd(day, -1*(datepart(day, @sdate)) + 1, @sdate)
    select @sdate, @edate
end

 

image

image

 

On 01/01/2010, this is what the dates will be:

image

image

No comments:

Post a Comment