Deterministic scalar function to get day of week for a date

后端 未结 11 1608
孤街浪徒
孤街浪徒 2021-01-13 00:10

SQL Server, trying to get day of week via a deterministic UDF.

Im sure this must be possible, but cant figure it out.

UPDATE: SAMPLE CODE..

C         


        
11条回答
  •  庸人自扰
    2021-01-13 00:20

    There is an already built-in function in sql to do it:

    SELECT DATEPART(weekday, '2009-11-11')
    

    EDIT: If you really need deterministic UDF:

    CREATE FUNCTION DayOfWeek(@myDate DATETIME ) 
    RETURNS int
    AS
    BEGIN
    RETURN DATEPART(weekday, @myDate)
    END
    GO
    SELECT dbo.DayOfWeek('2009-11-11')
    

    EDIT again: this is actually wrong, as DATEPART(weekday) is not deterministic.

    UPDATE: DATEPART(weekday) is non-deterministic because it relies on DATEFIRST (source).
    You can change it with SET DATEFIRST but you can't call it inside a stored function.

    I think the next step is to make your own implementation, using your preferred DATEFIRST inside it (and not considering it at all, using for example Monday as first day).

提交回复
热议问题