Pepe
Pepe

Reputation: 111

Use IF conditional in WHERE clause

I have a simple WHERE clause like:

WHERE
    [T].[DesignKey] = 5232
    AND
    (
        [TT].[TaskTypeCategoryId] ='8f08640b-bc74-e811-80dc-509a4c609460'
        OR
        [TT].[TaskTypeCategoryId] = '15F1F492-0CAC-E811-8421-C81F66DACA6A'
    )
    AND
    [TA].[EmpKey] = 58

Now I want to filter if this condition is true SecId > 4 filter by [TA].[EmpKey] = 58 If not just don't apply this filter so I do like:

WHERE
    [T].[DesignKey] = 5232
    AND
    (
        [TT].[TaskTypeCategoryId] ='8f08640b-bc74-e811-80dc-509a4c609460'
        OR
        [TT].[TaskTypeCategoryId] = '15F1F492-0CAC-E811-8421-C81F66DACA6A'
    )
    AND
    (
        E.SecID > 4
        OR
        (
            [TA].[EmpKey] = 58
        )
    )

But it no works, it just don't applying filter if SecId comes with 5, what am I doing wrong? Regards

Upvotes: 0

Views: 72

Answers (2)

digital.aaron
digital.aaron

Reputation: 5707

You almost had it on your first attempt. You just have to add in a condition to allow for when SecID <= 4. You can add another couple of lines to do it with your original query, like this:

WHERE
    [T].[DesignKey] = 5232
    AND
    (
        [TT].[TaskTypeCategoryId] ='8f08640b-bc74-e811-80dc-509a4c609460'
        OR
        [TT].[TaskTypeCategoryId] = '15F1F492-0CAC-E811-8421-C81F66DACA6A'
    )
    AND
    (
        E.SecID <= 4
        OR
        (
            E.SecID > 4
            AND
            [TA].[EmpKey] = 58
        )
    )

Upvotes: 3

iSR5
iSR5

Reputation: 3498

Try this :

WHERE
    [T].[DesignKey] = 5232
    AND
    (
        [TT].[TaskTypeCategoryId] ='8f08640b-bc74-e811-80dc-509a4c609460'
        OR
        [TT].[TaskTypeCategoryId] = '15F1F492-0CAC-E811-8421-C81F66DACA6A'
    )
    AND 
    (
        CASE WHEN E.SecID > 4 THEN [TA].[EmpKey] ELSE 58 END = 58
    )

If true, it'll filter with EmpKey = 58, if false it'll simply says 58 = 58 which will be always true.

Upvotes: 0

Related Questions