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.
Although they tell us that they want it real bad, our primary goal is to ensure that we dont actually give it to them that way.
Although change is inevitable, change for the better is not.
Just because you can do something in PowerShell, doesnt mean you should. Helpful Links:
How to post code problemsHow to post performance problemsForum FAQs