使用 T-SQL 计算当日日期、本周第一天与最后一天

--当日日期
DECLARE @Today NVARCHAR(100);
SET @Today = DATENAME(YEAR, GETDATE()) + '-' + DATENAME(MONTH, GETDATE()) + '-' + DATENAME(DAY, GETDATE());

--本周第一天与最后一天
DECLARE @FirstDay INT, @LastDay INT
SET @FirstDay = 1
SET @LastDay = (@FirstDay - 1 + 6) % 7 + 1

--当日周几
DECLARE @TodayWeek INT
SET @TodayWeek = (((@@DATEFIRST - 1) + DATEPART(WEEKDAY, @Today) % 7) + 7 - 1) % 7 + 1

--计算本周第一天
DECLARE @DateFirst DATETIME
SET @DateFirst = @Today + ' 00:00:00'
SET @DateFirst = DATEADD(WEEKDAY, @FirstDay - @TodayWeek, @DateFirst)

--计算本周最后一天
DECLARE @DateLast DATETIME
SET @DateLast = @Today + ' 23:59:59'
SET @DateLast = DATEADD(WEEKDAY, @LastDay - @TodayWeek, @DateLast)

--输出检查
SELECT @Today AS 当日日期, @TodayWeek AS 今天周几, @FirstDay AS 第一天周几, @LastDay AS 最后一天周几, @DateFirst AS 本周第一天, @DateLast AS 本周最后一天

对于任意的本周第一天与最后一天还有些 bug,不通用,暂时先不研究了,等后期用到再改

posted @ 2016-09-07 15:35  不是豆豆  阅读(1421)  评论(0编辑  收藏  举报
友情链接:迷途