As much as I love Tally Tables and as high performing as they can be, I find that pure math will frequently beat it (although I've not tested it in this case). This includes a "short circuit" for Tuesday thru Saturday (since we're not considering holidays, the 5th workday is ALWAYS the 7th of the month if the month starts on any of those days). The FROM clause in the following is the good ol' fashioned, backwards compatible way of converting separate INTs for Month and Year to a DATETIME for the first of that month. The number 22801 is 1900*12 months + 1 to get rid of the current month.
I've also made it so the code is not dependent on the value of DATEFIRST so that this can easily be incorporated into a high performance iSF (Inline Scalar Function which is really an Inline Table Valued Function that returns a single value).
DECLARE @pMonth INT
SELECT @pMonth = 11
,@pYear = 2013
SELECT FifthWeekDay =
WHEN DATEDIFF(dd,-1,ca.FirstOfMonth)%7 > 1 -- -1 is a Sunday
ELSE 6-DATEDIFF(dd,-1,ca.FirstOfMonth)%7 -- -1 is a Sunday
FROM (SELECT DATEADD(mm,@pYear*12-22801+@pMonth,0))ca(FirstOfMonth)
Someone with more caffeine in their system might be able to simplify this even more. :-D
is pronounced ree-bar and is a Modenism for R
First step towards the paradigm shift of writing Set Based code: Stop thinking about what you want to do to a row... think, instead, of what you want to do to a column.
If you think its expensive to hire a professional to do the job, wait until you hire an amateur. -- Red Adair
How to post code problemsHow to post performance problemsForum FAQs