Deterministic scalar function to get day of week for a date

后端 未结 11 1531
孤街浪徒
孤街浪徒 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:36

    Slightly similar approach to aforementioned solution, but just a one-liner that could be used inside a function or inline for computed column.

    Assumptions:

    1. You don't have dates before 1899-12-31 (which is a Sunday)
    2. You want to imitate @@datefirst = 7
    3. @dt is smalldatetime, datetime, date, or datetime2 data type

    If you'd rather it be different, change the date '18991231' to a date with the weekday that you'd like to equal 1. The convert() function is key to making the whole thing work - cast does NOT do the trick:

    ((datediff(day, convert(datetime, '18991231', 112), @dt) % 7) + 1)

提交回复
热议问题