sql server - T-SQL to get dates -
i've ssrs sales report need pass dates previous month's start date , end date able pass using below code. however, since sales report has data past year(2014) need pass dates last year well. below code gives startdate1 2015-02-01 , enddate1 2015-02-28. need dates past year 2014-02-01 startdate2 , 2014-02-28 enddate2
select dateadd(month, datediff(month, '19000201', getdate()), '19000101') startdate1, dateadd(month, datediff(month, '19000101', getdate()), '18991231') enddate1
since last day of month can vary, important thing first day of current month year. can calculate other 3 values.
you expressions in parameters' default values instead.
start of month =today.adddays(1-today.day) end of month =today.adddays(1-today.day).addmonths(1).adddays(-1) start of month last year =today.adddays(1-today.day).addyears(-1) end of month last year: =today.adddays(1-today.day).addyears(-1).addmonths(1).adddays(-1)
but if want in sql, can. note below i'm describing how start of month , using placeholder variables in other expressions clarity.
--start of month dateadd(month, datediff(month, 0, getdate()), 0) --end of month dateadd(day, -1, dateadd(month, 1, @startofmonth)) --start of month last year dateadd(year, -1, @startofmonth) --end of month last year dateadd(day, -1, dateadd(month, 1, @startofmonthlastyear))
those pieces. put them 1 giant, hard read select statement so:
select dateadd(month, datediff(month, 0, getdate()), 0) startdate1, dateadd(day, -1, dateadd(month, 1, dateadd(month, datediff(month, 0, getdate()), 0))) enddate1, dateadd(year, -1, dateadd(month, datediff(month, 0, getdate()), 0)) startdate2, dateadd(day, -1, dateadd(month, 1, dateadd(year, -1, dateadd(month, datediff(month, 0, getdate()), 0)))) enddate2
now see why recommend using internal parameters can leverage .net datetime class methods.
Comments
Post a Comment