在WHERE子句中使用IF条件

时间:2018-10-03 22:16:10

标签: sql-server tsql

我有一个简单的WHERE子句,例如:

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

现在我要过滤此条件是否为真SecId > 4过滤器,按[TA].[EmpKey] = 58过滤,如果不只是不应用此过滤器,那么我喜欢:

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
        )
    )

但是没有用,如果SecId带有5,就不应用过滤器,我在做什么错?问候

2 个答案:

答案 0 :(得分:3)

您几乎在第一次尝试时就拥有了它。您只需要添加一个条件以允许SecID <=4。您可以添加另外几行以对原始查询进行操作,例如:

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
        )
    )

答案 1 :(得分:0)

尝试一下:

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
    )

如果为true,则将使用EmpKey = 58进行过滤;如果为false,则只会说58 = 58,这将始终为true。