Datefirst in SQL Server Function

Hans Furmann 40 Reputation points
2024-02-21T11:22:39.1466667+00:00

Hello, I have a SQL server function where I have to find the weekday number. Now it seems that it depends on the user which result I get. With some users I get a 7 for Sunday, with others a 1. I've inserted Set DATEFIRST into this function, but this entry is deleted when I save the function. Can someone tell me what I have to do to always get the same number for a weekday, regardless of the respective user and his environment? I already have this problem when I run the function in the editor or execute the function using a Select statement Example: SELECT WeekDaty FROM MyFunction ('2024-1-1') Regards

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
14,492 questions
{count} votes

Accepted answer
  1. Erland Sommarskog 119.9K Reputation points MVP
    2024-02-21T22:52:11.22+00:00

    SET commands are not permitted in function.

    You can retrieve the current setting of the DATEFIRST option with the function @@datefirst. Here is an example:

    CREATE OR ALTER FUNCTION MyFunkyOne(@a date) RETURNS int AS
    BEGIN 
       RETURN (datepart(dw, @a) + @@datefirst - 1) % 7 
    END 
    go
    SET DATEFIRST 7
    SELECT dbo.MyFunkyOne('2024-02-21')
    go
    SET DATEFIRST 1
    SELECT dbo.MyFunkyOne('2024-02-21')
    go
    SET DATEFIRST 2
    SELECT dbo.MyFunkyOne('2024-02-21')
    

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.