Deterministic scalar function to get day of week for a date

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

    Although this is old. Commenting simple answer to help future readers. @liver-larson was almost correct. Made a wrong assumption of epoch time 0 (Jan 1st, 1900) being a Sunday. It is actually a Monday.

    Wrong code - https://stackoverflow.com/a/20481717/2012977

    datediff(dd,0,[DateColumn]) % 7 + 1
    

    Correction

    datediff(dd,-1,[DateColumn]) % 7 + 1
    

    I like this answer because there is no date conversion happening and guaranteed deterministic.

    Unit test of code. Sadly SqlFiddle down at the moment of writing. Note hardcoding column value here. Expect column to be a date type.

    SELECT DATEPART(WEEKDAY, '2020-06-14'), DATEDIFF(dd, -1, '2020-06-14') % 7 + 1
    SELECT DATEPART(WEEKDAY, '2020-06-15'), DATEDIFF(dd, -1, '2020-06-15') % 7 + 1
    SELECT DATEPART(WEEKDAY, '2020-06-16'), DATEDIFF(dd, -1, '2020-06-16') % 7 + 1
    SELECT DATEPART(WEEKDAY, '2020-06-17'), DATEDIFF(dd, -1, '2020-06-17') % 7 + 1
    SELECT DATEPART(WEEKDAY, '2020-06-18'), DATEDIFF(dd, -1, '2020-06-18') % 7 + 1
    SELECT DATEPART(WEEKDAY, '2020-06-19'), DATEDIFF(dd, -1, '2020-06-19') % 7 + 1
    SELECT DATEPART(WEEKDAY, '2020-06-20'), DATEDIFF(dd, -1, '2020-06-20') % 7 + 1
    

提交回复
热议问题