Deterministic scalar function to get day of week for a date

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

    Make a function, and have @dbdate varchar(8) as your input variable.

    Have it return the following:

    RETURN (DATEDIFF(dd, -1, convert(datetime, @dbdate, 112)) % 7)+1;
    

    The value 112 is the sql style YYYYMMDD.

    This is deterministic because the datediff does not receive a string input, if it were to receive a string it would no longer work because it internally converts it to a datetime object. Which is not deterministic.

提交回复
热议问题