Skip to content
 

Conditional Where Clause

You are currently browsing comments. If you would like to return to the full story, you can read the full entry here: “Conditional Where Clause”.

6 Comments

  1. Ramon says:

    Wow Greate tutorial…. Thanx

  2. rajani says:

    Thank You!!
    I stumbled accross this today and it helped fix up my code perfectly.

  3. Harvey says:

    Dereck…Nevermind. I figured out what needed to be done. Thanks anyway!

    -Harvey

  4. Harvey says:

    Why it keeps gettign cut off…I don’t know. But here is another attempt at pasting it in;

    CASE WHEN DATEPART(mm, GetDate()) = 1 then
    (DatePart(dd, pl.Plcmt_From_Dt) >= 11
    and DatePart(mm, pl.Plcmt_From_Dt) = 12
    and DatePart(Year, pl.Plcmt_From_Dt) = DatePart(Year, GetDate())-1
    OR
    DatePart(dd, pl.Plcmt_From_Dt) = 11 AND (DATEPART(mm, pl.Plcmt_From_Dt) = DATEPART(mm, GETDATE())-1
    and DATEPART(Year, pl.Plcmt_From_Dt) = DATEPART(Year, GETDATE()))
    OR
    DATEPART(dd, pl.Plcmt_From_Dt) <= 10 AND DATEPART(mm, pl.Plcmt_From_Dt) = DATEPART(mm, GETDATE()) AND DATEPART(Year, pl.Plcmt_From_Dt) = DATEPART(Year, GETDATE())
    end

  5. Harvey says:

    Dereck,

    I just subscribed to your newsletter and commented after using one of your posts to use the correct syntax for CAST functions. I have a question and am hoping that you can help me. I am writing a query where I am attempting to use a CASE expression in the WHERE clause using DATEPART. I am trying to build it so that if the month that a report is being run is January then to return records that are from the 11th of December of last year through the 10th of January of the current year ELSE return the records for the same date range of the current year. The code that I have is as follows;

    CASE WHEN DATEPART(mm, GetDate()) = 1 then
    (DatePart(dd, pl.Plcmt_From_Dt) >= 11
    and DatePart(mm, pl.Plcmt_From_Dt) = 12
    and DatePart(Year, pl.Plcmt_From_Dt) = DatePart(Year, GetDate())-1
    OR
    DatePart(dd, pl.Plcmt_From_Dt) = 11 AND (DATEPART(mm, pl.Plcmt_From_Dt) = DATEPART(mm, GETDATE())-1
    and DATEPART(Year, pl.Plcmt_From_Dt) = DATEPART(Year, GETDATE()))
    OR
    DATEPART(dd, pl.Plcmt_From_Dt) ‘.

    Any help you can offer would be greatly appreciated!

    Sincerely,
    Harvey

  6. Eden says:

    Thank you so much for this posting. I used it in a query at work and it fit the bill 100%. Saved me a bunch of work

post a comment OR Post Your Question on our ASK! Community!