在一年的第一天动态设置datefirst

时间:2016-03-13 07:03:45

标签: sql sql-server sql-server-2012

首先将日期设置为我的SQL查询,我遇到了问题。以下是我使用IF,Else IF设置的代码。但我需要一个sql语句而不是IF,Else IF。

DECLARE @CurrentDate DATE, @FirstDayOfWeek INT
SELECT @CurrentDate = DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0)
SELECT @FirstDayOfWeek = DATEPART(DW,@CurrentDate)

IF @FirstDayOfWeek = 6
    SET DATEFIRST 5; --friday
ELSE IF @FirstDayOfWeek = 7
    SET DATEFIRST 6; --sunday
--AND SO ON

3 个答案:

答案 0 :(得分:2)

DATEPART(DW, . . .)的结果取决于@@DATEFIRST的当前值,因此您需要在设置@@DATEFIRST的新值时将其考虑在内。最简单的方法是将@@DATEFIRST设置为1,获取当周的当天,然后将@@DATEFIRST设置为该值。

顺便说一句,如果您只想要日期时间的日期,可以将其投射到DATE。但最终,没有必要将日期时间转换为日期,因为DATEPART(DW, . . .)的结果将是相同的。

DECLARE @CurrentDate DATE, @CurrentDayOfWeek INT
SET @CurrentDate = CAST(GETDATE() AS DATE)
SET DATEFIRST 1 -- normalize first day of week
SET @CurrentDayOfWeek = DATEPART(DW, @CurrentDate)
SET DATEFIRST @CurrentDayOfWeek

或者

DECLARE @CurrentDayOfWeek INT
SET DATEFIRST 1 -- normalize first day of week
SET @CurrentDayOfWeek = DATEPART(DW, GETDATE())
SET DATEFIRST @CurrentDayOfWeek

示例:

DECLARE @CurrentDayOfWeek INT
SET DATEFIRST 1 -- normalize first day of week to Monday
SET @CurrentDayOfWeek = DATEPART(DW, '2016-01-01') -- a Friday, which will be 5 because first day of week is currently 1
SET DATEFIRST @CurrentDayOfWeek -- first day of week is now 5 (Friday)

答案 1 :(得分:1)

我知道你的问题提到了DATEFIRST,但是你有什么理由不根据自今年第一年以来的天数来计算它吗?

SELECT ((DATEPART(DY, GETDATE()) - 1) % 7) + 1

旧答案:

请注意,如果DATEFIRST已从默认值7更改,则此功能将不再有效,因为DATEPART(dw,...)将返回不同的值。与SET DATEFIRST一起使用的值是总是 1 =星期一,7 =星期天等等。您可以提前SET DATEFIRST 7提前...

基本上你正在做的是减去1并且如果你达到0则回滚到7.你可以使用mod运算符(%):

答案 2 :(得分:0)

看看这是否适合你

DECLARE @CurrentDate DATETIME, @FirstDayOfWeek INT
SELECT @CurrentDate = DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0)
SELECT @FirstDayOfWeek = DATEPART(DW,@CurrentDate)

SELECT @FirstDayOfWeek = (SELECT CASE @FirstDayOfWeek
WHEN 6 THEN 5
WHEN 7 THEN 6
END )

SET DATEFIRST @FirstDayOfWeek