如何在使用DATEPART时处理DATEFIRST

时间:2016-07-29 15:03:15

标签: sql-server tsql

-- SET DATEFIRST to U.S. English default value of 7.  
SET DATEFIRST 7;
SELECT
  @@DATEFIRST;
SELECT
  GETDATE()
, DATEPART(dw , GETDATE()) AS DayOfWeek;  
-- January 1, 1999 is a Friday. Because the U.S. English default   
-- specifies Sunday as the first day of the week, DATEPART of 1999-1-1  
-- (Friday) yields a value of 6, because Friday is the sixth day of the   
-- week when you start with Sunday as day 1.  

SET DATEFIRST 3;
SELECT
  @@DATEFIRST;
-- Because Wednesday is now considered the first day of the week,  
-- DATEPART now shows that 1999-1-1 (a Friday) is the third day of the   
-- week. The following DATEPART function should return a value of 3.  
SELECT
  GETDATE()
, DATEPART(dw , GETDATE()) AS DayOfWeek;
SET DATEFIRST 7;

无论DATEFIRST设置如何,我们如何处理DATEPART(1 =周日总是)?

我真的不想做一个案子并减去......

3 个答案:

答案 0 :(得分:2)

对我来说这总是很荒谬,怎么样呢?

select datediff(day,0, getdate()) % 7

其中6代表星期日

或者你可以做到

select (datediff(day,0, '2016-07-31') - 5) % 7

得到Sun = 1,Mon = 2,Tue = 3 ......等等

或者你可以做这个小提琴

select (datepart(weekday,get_date()) + @@datefirst - 1) % 7 + 1

似乎适用于所有日期部分

    set datefirst  5

select (datepart(weekday,'2016-07-31') + @@datefirst - 1) % 7 + 1
select (datepart(weekday,'2016-08-01') + @@datefirst - 1) % 7 + 1
select (datepart(weekday,'2016-08-02') + @@datefirst - 1) % 7 + 1
select (datepart(weekday,'2016-08-03') + @@datefirst - 1) % 7 + 1
select (datepart(weekday,'2016-08-04') + @@datefirst - 1) % 7 + 1
select (datepart(weekday,'2016-08-05') + @@datefirst - 1) % 7 + 1
select (datepart(weekday,'2016-08-06') + @@datefirst - 1) % 7 + 1
select (datepart(weekday,'2016-08-07') + @@datefirst - 1) % 7 + 1

答案 1 :(得分:1)

也许不是最优雅的,但是你可以将其设置为7,然后再回到100%

之后的状态,而不是进行减法。
DATEPART

答案 2 :(得分:1)

此代码选择星期一作为星期的第一天,无论引擎中的设置如何:

((datepart(DW, @YourDateVariable) + @@DATEFIRST + 5) % 7) + 1

通过在模数运算符之前添加@@DATEFIRST值,它忽略了SQL引擎中的datefirst设置。

值5是将星期一作为一周的第一天 星期日作为一周的第一天加6 星期六作为一周的第一天然后加0 等等剩下的一周。