看看我的功能,请告诉我哪里出错,或者有什么简单的方法可以做到这一点
DECLARE @Day varchar(20);
DECLARE @Today varchar(20);
DECLARE @StartDate datetime;
DECLARE @EndDate datetime;
DECLARE @NOW datetime;
SET @NOW=GETUTCDATE();
SET @Today=CONVERT(varchar(20),(select datename(dw,@NOW)))
SET @Day='Monday';
DECLARE @intFlag INT
SET @intFlag = 0
WHILE (@intFlag <7)
BEGIN
IF @Today=@Day
BEGIN
SET @StartDate=DATEADD(day,-6,@NOW);
SET @EndDate=DATEADD(day,0,@NOW);
PRINT @StartDate;
BREAK;
END
SET @NOW=DATEADD(day,1,@NOW);
SET @intFlag = @intFlag + 1
END
不打印任何输出
由于
答案 0 :(得分:1)
没有输出,因为你不断改变@NOW,但不是@Today。这意味着你永远不会进入IF @ Today = @ Day,除非GETUTCDATE()返回星期一。我猜想,既然你继续迭代@NOW产生@Today,你想在@NOW的工作日保持@Today。
我冒昧地将@Today的更新添加到您的代码中:
DECLARE @Day varchar(20);
DECLARE @Today varchar(20);
DECLARE @StartDate datetime;
DECLARE @EndDate datetime;
DECLARE @NOW datetime;
SET @NOW=GETUTCDATE();
SET @Today=CONVERT(varchar(20),(select datename(dw,@NOW)))
SET @Day='Monday';
DECLARE @intFlag INT
SET @intFlag = 0
WHILE (@intFlag <7)
BEGIN
IF @Today=@Day
BEGIN
SET @StartDate=DATEADD(day,-6,@NOW);
SET @EndDate=DATEADD(day,0,@NOW);
PRINT @StartDate;
BREAK;
END
SET @NOW=DATEADD(day,1,@NOW);
SET @Today=CONVERT(varchar(20),(select datename(dw,@NOW)))
SET @intFlag = @intFlag + 1
END
修改强>
阅读完评论后,这里有更多代码。我选择过去的星期二作为参考(01.01.1980),以便星期一将是案例构造中的0。我知道这不太理想,但无论如何都要尝试:
declare @Day varchar(20);
declare @pastweekday datetime;
set @Day = 'Monday';
set @pastweekday = dateadd(day, case when @Day = 'Monday' then 0
when @Day = 'Tuesday' then 1
when @Day = 'Wednesday' then 2
when @Day = 'Thursday' then 3
when @Day = 'Friday' then 4
when @Day = 'Saturday' then 5
when @Day = 'Sunday' then 6
end
, '19800101')
SELECT DATEADD(day, (DATEDIFF (day, @pastweekday, GETUTCDATE()) / 7) * 7, @pastweekday)
答案 1 :(得分:1)
如何使用它来检索一周的第一天?
SELECT DATEADD(day, DATEPART(weekday, GETUTCDATE()) * -1, GETUTCDATE())
顺便说一下,更好的答案:Get first day of week in SQL Server