SQL DATEFIRST

SQL Server 的 DATEFIRST 设置函数将在一周的第一天设置为 1 到 7。如果您的默认语言是美国英语,则默认将 7(星期日)设置为第一天。DATEFIRST 的基本语法如下所示。

SET DATEFIRST { number (or number_variable) }

-- For example,
SET DATEFIRST 4;

下面的 SQL Server 表将向您展示值及其对应的星期名称

一周的第一天
1星期一
2星期二
3星期三
4星期四
5星期五
6星期六
7星期日

SQL DATEFIRST 示例

在此示例中,我们将展示 SET DATEFIRST 如何影响星期几。

-- Default first Day
SELECT @@DATEFIRST AS 'First day of the Week'

-- Set the DateFirst Value to 3 (Wednesday)
SET DATEFIRST 3;

-- Now let me select the first Day Value
SELECT @@DATEFIRST AS 'First day of the Week'

SELECT GETDATE() AS 'Today', 
       DATEPART(dw, GETDATE()) AS 'Today Number'

尽管今天是星期三,但 dw 的 DATEPART 返回 1(而不是 4),因为我们将第一天设置为星期三。因此,计数将从星期三开始(星期三=1,星期四=2,星期五=3...)

DATEFIRST Example