SET DATEFIRST in FUNCTION

前端 未结 4 1044
悲哀的现实
悲哀的现实 2020-12-16 01:37

I want to SET DATEFIRST in my function but it is not allowed.

SET DATEFIRST 1

I can add the code in a SP and call the SP from the function

4条回答
  •  囚心锁ツ
    2020-12-16 02:27

    Alternative way is to explicitly specify the first day of week value as parameter and avoid depending on @@DATEFIRST setting. You can use the following formula to achieve that in your function:

    (DATEPART(dw, GETDATE()) + @@DATEFIRST + 6 - @WeekStartDay) % 7 + 1
    

    where @WeekStartDay is the first day of the week you want for your system (from 1 to 7 which means from Monday to Sunday).

    I have wrapped it into below function so we can reuse it easily:

    CREATE FUNCTION [dbo].[GetDayInWeek](@InputDateTime DATETIME, @WeekStartDay INT)
    RETURNS INT
    AS
    BEGIN
        --Note: @WeekStartDay is number from [1 - 7] which is from Monday to Sunday
        RETURN (DATEPART(dw, @InputDateTime) + @@DATEFIRST + 6 - @WeekStartDay) % 7 + 1 
    END
    

    Example usage: GetDayInWeek('2019-02-04 00:00:00', 1)

    It is equivalent to following (but independent to DATEFIRST setting):

    SET DATEFIRST 1
    DATEPART(dw, '2019-02-04 00:00:00')
    

提交回复
热议问题