日期:2014-05-17 浏览次数:20425 次
--星期一 2013-12-07 23:51:21.150
select dateadd(dd,-datepart(weekday,getdate())+2,getdate())
--星期日 2013-12-15 23:56:50.437
select dateadd(dd,-datepart(weekday,getdate())+8,getdate())
declare @x datetime, @weekBegin datetime, @weekEnd datetime
select @x='2013-12-08' --> 输入日期
select @weekBegin=dateadd(d,-1*number,@x)
from master.dbo.spt_values
where type='P' and number between 0 and 6
and datepart(dw,dateadd(d,-1*number,@x))=2
select @weekEnd=dateadd(d,number,@x)
from master.dbo.spt_values
where type='P' and number between 0 and 6
and datepart(dw,dateadd(d,number,@x))=1
select @weekBegin '星期一',@weekEnd '星期日'
/*
星期一 星期日
----------------------- -----------------------
2013-12-02 00:00:00.000 2013-12-08 00:00:00.000
(1 row(s) affected)
*/
--定义给定的一天
DECLARE @Date DATETIME = GETDATE();
SELECT @Date AS '目前时间'
,DATEADD(DD,-1,@Date) AS '前一天'
,DATEADD(DD,1,@Date) AS '后一天'
/*月计算*/
,DATEADD(MONTH,DATEDIFF(MONTH,0,@Date),0) AS '月初'--在SQL Server中0 代表1900-01-01,通过月运算,保证日恒久为1号
,DATEADD(DD,-1,DATEADD(MONTH,1+DATEDIFF(MONTH,0,@Date),0)) AS '月末(精确到天)'--找到下月初再扣减1天,建议使用DATEADD而不要直接“-1”
,DATEADD(SS,-1,DATEADD(MONTH,1+DATEDIFF(MONTH,0,@Date),0)) AS '月末(精确到datetime的小数位)'
,DATEADD(MONTH,DATEDIFF(MONTH,0,@Date)-1,0) AS '上月第一天'
,DATEADD(DAY,-1,DATEADD(DAY,1-DATEPART(DAY,@Date),@Date)) AS '上月最后一天'
,DATEADD(MONTH,DATEDIFF(MONTH,0,@Date)+1,0) AS '下月第一天'
,DATEADD(DAY,-1,DATEADD(MONTH,2,DATEADD(DAY,1-DATEPART(DAY,@Date),@Date)))