变量名称为Sql Server 2012 WHERE子句中的列

时间:2014-07-31 17:17:27

标签: sql-server where-clause

我尝试过各种各样的方法,这是我确定可以使用的方法 - 但是alter storedprocedure在CASE系列中失败了。

     WHERE v.State_combined != ''

    CASE WHEN @component = 'Component 1' 
        THEN
        AND (v.[Component_1_Status] IN ('SUBMITTED', 'INCOMPLETE', 'PURCHASED')) 
        WHEN @component = 'Component 2' 
        THEN
        AND (v.[Component_2_Status] IN ('SUBMITTED', 'INCOMPLETE', 'PURCHASED'))
        ELSE
        AND (v.[Component_1_Status] IN ('SUBMITTED', 'INCOMPLETE', 'PURCHASED') or       v.[Component_2_Status] IN ('SUBMITTED', 'INCOMPLETE', 'PURCHASED'))
        END

    AND (@state IS null OR v.STATE_COMBINED = @state)

2 个答案:

答案 0 :(得分:1)

CASE..WHEN

的示例解决方案
WHERE
    v.State_combined != ''
    AND 1 = CASE
        WHEN @component = 'Component 1' AND (v.[Component_1_Status] IN ('SUBMITTED', 'INCOMPLETE', 'PURCHASED')) THEN 1
        WHEN @component = 'Component 2' AND (v.[Component_2_Status] IN ('SUBMITTED', 'INCOMPLETE', 'PURCHASED')) THEN 1
        WHEN (
            v.[Component_1_Status] IN ('SUBMITTED', 'INCOMPLETE', 'PURCHASED')
            OR v.[Component_2_Status] IN ('SUBMITTED', 'INCOMPLETE', 'PURCHASED')
        ) THEN 1
        ELSE 0
END
AND (@state IS null OR v.STATE_COMBINED = @state)

CASE..WHEN将返回一个值,您不能将其用作控制结构。

另一种解决方案(仅限boolen逻辑):

WHERE
    v.State_combined != ''
    AND (
        (@component = 'Component 1' AND v.[Component_1_Status] IN ('SUBMITTED', 'INCOMPLETE', 'PURCHASED'))
        OR (@component = 'Component 2' AND v.[Component_2_Status] IN ('SUBMITTED', 'INCOMPLETE', 'PURCHASED'))
        OR (
            @component NOT IN ('Component 1', 'Component 2')
            AND (
                v.[Component_1_Status] IN ('SUBMITTED', 'INCOMPLETE', 'PURCHASED')
                OR v.[Component_2_Status] IN ('SUBMITTED', 'INCOMPLETE', 'PURCHASED')
            )
        )
    )
    AND (@state IS null OR v.STATE_COMBINED = @state)

答案 1 :(得分:0)

WHERE  v.State_combined != ''
       AND
       (
           (
               @component = 'Component 1' 
               AND 
               v.[Component_1_Status] IN ('SUBMITTED', 'INCOMPLETE', 'PURCHASED')
           ) 
           OR
           (
               @component = 'Component 2' 
               AND 
               v.[Component_2_Status] IN ('SUBMITTED', 'INCOMPLETE', 'PURCHASED')
           )
           OR
           (
               v.[Component_1_Status] IN ('SUBMITTED', 'INCOMPLETE', 'PURCHASED') 
               OR       
               v.[Component_2_Status] IN ('SUBMITTED', 'INCOMPLETE', 'PURCHASED')
           )
       )
       AND 
       (
           @state IS NULL 
           OR 
           v.STATE_COMBINED = @state
       )