如何检查where子句中的COndition

时间:2018-03-05 11:56:43

标签: sql-server sql-server-2008 case where-clause

SELCT * FROM @Locations Loc
    INNER JOIN SubProposal SP ON SP.MasterProposalId = Loc.ProposalId
    WHERE SP.EndEffectiveDate = @EndEffectiveDate
    AND ISNULL(SP.Data.value('(/*/IsRemovedByEndorsement)[1]', 'bit'), 0) = 0
    CASE WHEN (@AS22_RightOfPledgeNum <> '') THEN
    AND (SP.Data.value('(/*/Answers/AnswersList/Entry[@key="as22_RightOfPledgeNum"]/value)[1]', 'nvarchar(max)')= @AS22_RightOfPledgeNum) ELSE 1 
    END

它在案例条件附近抛出错误&#34; CASE附近的语法不正确

我如何才能检查上述条件我只需要在

时包含此声明
 CASE WHEN (@AS22_RightOfPledgeNum <> '') THEN
    AND (SP.Data.value('(/*/Answers/AnswersList/Entry[@key="as22_RightOfPledgeNum"]/value)[1]', 'nvarchar(max)')= @AS22_RightOfPledgeNum) ELSE 1 
    END

1 个答案:

答案 0 :(得分:1)

对不起。下面的第一个答案是不对的。在我发布之后我意识到我误读了查询。您需要基于变量的不同WHERE子句。因此,您需要在查询之外使用IF语句,因为SQL无法以您尝试使用CASE的方式理解CASE。 我不确定我明白你在这里要做什么。您的WHERE语句需要有条件进行测试。如果我理解你的观点,

IF @AS22_RightOfPledgeNum <> ''
BEGIN
        SELECT * FROM @Locations Loc
        INNER JOIN SubProposal SP 
            ON SP.MasterProposalId = Loc.ProposalId
        WHERE SP.EndEffectiveDate = @EndEffectiveDate
            AND ISNULL(SP.Data.value('(/*/IsRemovedByEndorsement)[1]', 'bit'), 0) = 0
            AND (SP.Data.value('(/*/Answers/AnswersList/Entry[@key="as22_RightOfPledgeNum"]/value)[1]', 'nvarchar(max)')= @AS22_RightOfPledgeNum) 
ELSE
        SELECT * FROM @Locations Loc
        INNER JOIN SubProposal SP 
            ON SP.MasterProposalId = Loc.ProposalId
        WHERE SP.EndEffectiveDate = @EndEffectiveDate
            AND ISNULL(SP.Data.value('(/*/IsRemovedByEndorsement)[1]', 'bit'), 0) = 0;

旧的答案(不完全是钱): 您正在尝试根据行中的数据应用不同的WHERE子句。但是,WHERE子句应用于完整数据集。您需要将数据分成两组,并分别将正确的WHERE子句应用于每个集合。

将CASE条件添加到JOIN条件,将数据限制限制为您感兴趣的行,然后将所需的WHERE条件应用于每个集合。

这样的事情:

SELCT * FROM @Locations Loc
    INNER JOIN SubProposal SP 
        ON SP.MasterProposalId = Loc.ProposalId
        AND @AS22_RightOfPledgeNum <> ''

        WHERE SP.EndEffectiveDate = @EndEffectiveDate
    AND ISNULL(SP.Data.value('(/*/IsRemovedByEndorsement)[1]', 'bit'), 0) = 0
    AND (SP.Data.value('(/*/Answers/AnswersList/Entry[@key="as22_RightOfPledgeNum"]/value)[1]', 'nvarchar(max)')= @AS22_RightOfPledgeNum) 
UNION ALL
SELCT * FROM @Locations Loc
    INNER JOIN SubProposal SP 
        ON SP.MasterProposalId = Loc.ProposalId
        AND @AS22_RightOfPledgeNum = ''

    WHERE SP.EndEffectiveDate = @EndEffectiveDate
    AND ISNULL(SP.Data.value('(/*/IsRemovedByEndorsement)[1]', 'bit'), 0) = 0;