Wednesday, 22 July 2015

TSQL: Dates

Date format requirement: YYYY-MM-DD

  • Get today's date
          select cast(getdate() as date)  
  • Get first day of the current month
          select cast(dateadd(dd, -DAY(getdate())+1, GETDATE()) as date)         
          select cast(left(cast(getdate() as date), 8) as varchar) + '01'
  • Get last day of the current month 
          select cast(DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0)) as DATE)
  • Get first day of the previous month
          select cast(dateadd(dd,-(day(dateadd(m, -1, GETDATE()))-1),dateadd(m, -1, GETDATE())) as DATE)
  • Get last day of the previous month
          select cast(DATEADD(dd,-(DAY(GETDATE())),GETDATE()) as date)

No comments:

Post a Comment