这有效:
SELECT
DATEADD(wk, DATEDIFF(wk,'19000108',GETDATE()),'19000101'),
DATEADD(wk, DATEDIFF(wk,'19000108',GETDATE()),'19000107')
目前的星期一和星期日它将返回前一周的日期。
它很简洁,但在我看来不太可读 - 因为它依赖于1900年1月8日是一个星期天 - 这不是很多人记得的东西!
什么是具有相同功能的更简单易读的脚本替代方案?
答案 0 :(得分:3)
SELECT
DATEADD(DAY, (DATEPART(WEEKDAY, GETDATE()) * -1) - 5, GETDATE()),
DATEADD(DAY, (DATEPART(WEEKDAY, GETDATE()) * -1) + 1, GETDATE())
结果(当GETDATE()='2014-05-19 13:00:16.557'):
2014-05-12 13:00:16.557 2014-05-18 13:00:16.557
删除时间:
SELECT
CAST(FLOOR(CAST( DATEADD(DAY, (DATEPART(WEEKDAY, GETDATE()) * -1) - 5, GETDATE()) AS FLOAT)) AS DATETIME),
CAST(FLOOR(CAST( DATEADD(DAY, (DATEPART(WEEKDAY, GETDATE()) * -1) + 1, GETDATE()) AS FLOAT)) AS DATETIME)
结果:
2014-05-12 00:00:00.000 2014-05-18 00:00:00.000
一个更简单的版本,删除了时间但由于DATE类型可能不理想:
SELECT
CONVERT(DATE, DATEADD(DAY, (DATEPART(WEEKDAY, GETDATE()) * -1) - 5, GETDATE())),
CONVERT(DATE, DATEADD(DAY, (DATEPART(WEEKDAY, GETDATE()) * -1) + 1, GETDATE()))
答案 1 :(得分:2)
我可能会认为1900-01-01是星期一。
select DATEADD(week, datediff(week, 0, getdate()), 0)
然后从那里开始:
select DATEADD(week, -1, DATEADD(week, DATEDIFF(week, 0, getdate()), 0))
,DATEADD(day, -1, DATEADD(week, DATEDIFF(week, 0, getdate()), 0))