• David Smerchek (6/19/2013)


    SELECT DATEDIFF (day, Convert(Varchar(11),DATEADD(d,-(DAY(getdate())-1),getdate()),110), Convert(varchar(11),GETDATE(),110))

    - (2 * DATEDIFF(week, Convert(Varchar(11),DATEADD(d,-(DAY(getdate())-1),getdate()),110), Convert(varchar(11),GETDATE(),110)))

    - CASE WHEN DATEPART(weekday, DATEADD(d,-(DAY(getdate())-1),getdate()) + @@DATEFIRST) = 1 THEN 1 ELSE 0 END - CASE WHEN DATEPART(weekday, GETDATE() + @@DATEFIRST) = 1 THEN 1 ELSE 0 END

    -count(

    Case

    when '01/01/2013' between Convert(Varchar(11),DATEADD(d,-(DAY(getdate())-1),getdate()),110) and Convert(varchar(11),GETDATE(),110) then 1

    when '7/4/2013' between Convert(Varchar(11),DATEADD(d,-(DAY(getdate())-1),getdate()),110) and Convert(varchar(11),GETDATE(),110)then 1

    when '9/2/2013' between Convert(Varchar(11),DATEADD(d,-(DAY(getdate())-1),getdate()),110) and Convert(varchar(11),GETDATE(),110)then 1

    when '11/28/2013' between Convert(Varchar(11),DATEADD(d,-(DAY(getdate())-1),getdate()),110) and Convert(varchar(11),GETDATE(),110)then 1

    when '12/25/2013' between Convert(Varchar(11),DATEADD(d,-(DAY(getdate())-1),getdate()),110) and Convert(varchar(11),GETDATE(),110) then 1

    end) as WorkDays

    The problem with such code is that it uses hardcoded dates that must be updated every year. If you forget, you can really mess up a whole bunch of things. Using a Calendar table would likely be a much better solution.

    Whatever solution you use, at least add some error handling for when you run out of dates or have exceeded hardcoded expectations.

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    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.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)