SET DATEFIRST in FUNCTION

My usual workaround is to use "known-good" dates for my comparisons.

Say, for instance, that I need to check that a date is a saturday. Rather than relying on DATEFIRST or language settings (for using DATENAME), I instead say:

DATEPART(weekday,DateToCheck) = DATEPART(weekday,'20120714')

I know that 14th July 2012 was a Saturday, so I've performed the check without relying on any external settings.


The expression (DATEPART(weekday,DateToCheck) + @@DATEFIRST) % 7 will always produce the value 0 for Saturday, 1 for Sunday, 2 for Monday, etc.

So, I'd advise you to create a table:

CREATE TABLE WorkingDays (
    NormalisedDay int not null,
    DaysInMonth int not null,
    WorkingDays int not null
)

Populating this table is a one off exercise. NormalisedDay would be the value computed by the expression I've given above.

To compute the DaysInMonth given a particular date, you can use the expression:

DATEDIFF(day,
      DATEADD(month,DATEDIFF(month,0,DateToCheck),0),
      DATEADD(month,DATEDIFF(month,'20010101',DateToCheck),'20010201'))

Now all your function has to do is look up the value in the table.

(Of course, all of the rows where DaysInMonth is 28 will have 20 as their result. It's only the rows for 29,30 and 31 which need a little work to produce)


Instead of

SET DATEFIRST 1

You can do

SELECT (DATEPART(weekday, GETDATE()) + @@DATEFIRST - 2) % 7 + 1