SQL常用日期处理

 

-- 1.一个月第一天的
Select   DATEADD (mm,  DATEDIFF (mm, 0 , getdate ()),  0 )
-- 2009-05-01 00:00:00.000

Select   convert ( char ( 8 ), getdate (), 120 ) + ' 01 '
-- 2009-05-01

-- 2.本周的星期一
Select   DATEADD (wk,  DATEDIFF (wk, 0 , getdate ()),  0 )
-- 2009-05-11 00:00:00.000

-- 3.一年的第一天
Select   DATEADD (yy,  DATEDIFF (yy, 0 , getdate ()),  0 )
-- 2009-01-01 00:00:00.000

Select   convert ( char ( 4 ), getdate (), 120 ) + ' 01-01 '
-- 200901-01

-- 4.季度的第一天
Select   DATEADD (qq,  DATEDIFF (qq, 0 , getdate ()),  0 )
-- 2009-04-01 00:00:00.000

-- 5.当天的半夜
Select   DATEADD (dd,  DATEDIFF (dd, 0 , getdate ()),  0 )
-- 2009-05-12 00:00:00.000

-- 6.上个月的最后一天
Select   dateadd (ms, - 3 , DATEADD (mm,  DATEDIFF (mm, 0 , getdate ()),  0 ))
-- 2009-04-30 23:59:59.997

-- 7.去年的最后一天
Select   dateadd (ms, - 3 , DATEADD (yy,  DATEDIFF (yy, 0 , getdate ()),  0 ))
-- 2008-12-31 23:59:59.997

-- 8.本月的最后一天
Select   dateadd (ms, - 3 , DATEADD (mm,  DATEDIFF (m, 0 , getdate ()) + 1 0 ))
-- 2009-05-31 23:59:59.997

-- 9.本年的最后一天
Select   dateadd (ms, - 3 , DATEADD (yy,  DATEDIFF (yy, 0 , getdate ()) + 1 0 ))
-- 2009-12-31 23:59:59.997

-- 10.本月的第一个星期一
select   DATEADD (wk,  DATEDIFF (wk, 0 , dateadd (dd, 6 - datepart ( day , getdate ()), getdate ())),  0 )
-- 2009-05-04 00:00:00.000

你可能感兴趣的:(sql)