SQL DATEPART(dw,date) need monday = 1 and sunday = 7

后端 未结 12 566
[愿得一人]
[愿得一人] 2020-12-23 16:27

I have a Query where I get the WeekDay of a date but by default:

  • Sunday = 1

  • Moday = 2

  • etc.

相关标签:
12条回答
  • 2020-12-23 17:02

    You can use this formula regardless of DATEFIRST setting :

    ((DatePart(WEEKDAY, getdate()) + @@DATEFIRST + 6 - [first day that you need] ) % 7) + 1;
    

    for monday = 1

    ((DatePart(WEEKDAY, getdate()) + @@DATEFIRST + 6 - 1 ) % 7) + 1;
    

    and for sunday = 1

    ((DatePart(WEEKDAY, getdate()) + @@DATEFIRST + 6 - 7 ) % 7) + 1;
    

    and for friday = 1

    ((DatePart(WEEKDAY, getdate()) + @@DATEFIRST + 6 - 5 ) % 7) + 1;
    
    0 讨论(0)
  • 2020-12-23 17:03

    Another solution is the following:

    ISNULL(NULLIF(DATEPART(dw,DateField)-1,0),7)
    
    0 讨论(0)
  • 2020-12-23 17:05

    This is caused by the account the SQL Server service is run under. For example;

    If the SQL Server Service is run under DOMAIN\MyUserAccount then this will need to be a login and set with the relevant Language.

    If this account isn't set then SQL Server will default to the sa account and the Language that runs under.

    I found that our sa account was set to English which had Monday as DW = 2. The DOMAIN\MyUserAccount Account was setup and changed to British English and DW for Monday was being returned as 1.

    Hope this helps

    0 讨论(0)
  • 2020-12-23 17:09

    You can tell SQL Server to use Monday as the start of the week using DATEFIRST like this:

    SET DATEFIRST 1
    
    0 讨论(0)
  • 2020-12-23 17:09

    Looks like the DATEFIRST settings is the only way, but it's not possible to make a SET statement in a scalar/table valued function. Therefore, it becomes very error-prone to the colleagues following your code. (become a trap to the others)

    In fact, SQL server datepart function should be improved to accept this as parameter instead.

    At the meantime, it looks like using the English Name of the week is the safest choice.

    0 讨论(0)
  • 2020-12-23 17:11

    You can use a formula like:

    (weekday + 5) % 7 + 1
    

    If you decide to use this, it would be worth running through some examples to convince yourself that it actually does what you want.

    addition: for not to be affected by the DATEFIRST variable (it could be set to any value between 1 and 7) the real formula is :

    (weekday  + @@DATEFIRST + 5) % 7 + 1
    
    0 讨论(0)
提交回复
热议问题