内连接中的嵌套case语句

时间:2014-05-08 13:55:14

标签: sql sql-server-2008 tsql

我认为有问题可以通过case语句解决,但它一直拒绝我的sql。基本上,我在现有SQL中引入了一个新参数,需要根据它的不同做出不同的反应......听起来像是一个案例陈述给我,但它一直拒绝它。有什么想法吗?

原始

INNER JOIN T_CASE CF ON
(
    A.AWESOME_ID = CF.AWESOME_ID    
    // Several more awesome conditions
)
AND
(
    (
        cy.SOMEFLAG = 0
        AND CF.SOMEDATE IS NOT NULL
    )
    OR
    (
        cy.SOMEFLAG = 1
        AND CF.CASE_TYPE = 1
        AND CF.SOMEDATE IS NOT NULL
    )
)

尝试#1

INNER JOIN T_CASE CF ON
(
    A.AWESOME_ID = CF.AWESOME_ID    
    // Several more conditions
)
AND
(
    // Just this part is what the new parameter applies to
    CASE WHEN @NEWPARAM = 1 THEN
    (
        (
            cy.SOMEFLAG = 0
            AND CF.SOMEDATE IS NOT NULL
        )
        OR
        (
            cy.SOMEFLAG = 1
            AND CF.CASE_TYPE = 1
            AND CF.SOMEDATE IS NOT NULL
        )
    )
    ELSE
    (
        (
            cy.SOMEFLAG = 0
            AND CF.SOMEDATE IS NULL
        )
        OR
        (
            cy.SOMEFLAG = 1
            AND CF.CASE_TYPE = 0
            OR CF.SOMEDATE IS NULL
        )
    )
    END
)

2 个答案:

答案 0 :(得分:2)

一般来说,我认为在条件子句中使用基本逻辑结构更好,而不是case。你可以很容易地做到这一点:

INNER JOIN T_CASE CF ON
(
    A.AWESOME_ID = CF.AWESOME_ID    
    // Several more conditions
)
AND
(
        (
            @NEWPARAM = 1 AND
            cy.SOMEFLAG = 0 AND
            CF.SOMEDATE IS NOT NULL
        )
        OR
        (
            @NEWPARAM = 1 AND
            cy.SOMEFLAG = 1 AND
            CF.CASE_TYPE = 1 AND
            CF.SOMEDATE IS NOT NULL
        )
        OR
        (
            @NEWPARAM <> 1 AND
            cy.SOMEFLAG = 0 AND
            CF.SOMEDATE IS NULL
        )
        OR
        (
            @NEWPARAM <> 1 AND
            ((cy.SOMEFLAG = 1 AND CF.CASE_TYPE = 0) OR
             CF.SOMEDATE IS NULL
            )
        )
    )

答案 1 :(得分:0)

您不能使用case语句来动态地包含/排除SQL语句的某些部分,但您仍然可以获得类似的效果

INNER JOIN T_CASE CF ON
(
    A.AWESOME_ID = CF.AWESOME_ID    
    // Several more conditions
)
AND
(
    // Just this part is what the new parameter applies to
    1 = CASE WHEN 
        @NEWPARAM = 1 
        and 
        (
            cy.SOMEFLAG = 0
            AND CF.SOMEDATE IS NOT NULL
        )
        OR
        (
            cy.SOMEFLAG = 1
            AND CF.CASE_TYPE = 1
            AND CF.SOMEDATE IS NOT NULL
        )
        THEN 1
    CASE WHEN 
        @NEWPARAM <> 1 
        and
        (
            (
                cy.SOMEFLAG = 0
                AND CF.SOMEDATE IS NULL
            )
            OR
            (
                cy.SOMEFLAG = 1
                AND CF.CASE_TYPE = 0
                OR CF.SOMEDATE IS NULL
            )
        )
        THEN 1
    ELSE 0
    END
)

基本上,我们为符合条件的行返回1,为不符合行的行返回0,并将其与值1进行比较。