WHERE语句基于CASE语句

时间:2013-11-04 19:34:54

标签: sql sql-server

我正在尝试根据变量的值添加CASE语句:

WHERE DTH.PointPerson LIKE @userParam
    AND ActivityDate >= @startDateParam
    AND ActivityDate <= @endDateParam

    --new section below
    AND CASE (@orgTeamPK)
    WHEN '%' THEN
     (USR.[OrganizationalTeamId] LIKE @orgTeamPK OR USR.[OrganizationalTeamId] IS NULL)
     ELSE
     (USR.[OrganizationalTeamId] LIKE @orgTeamPK)

但是我的语法似乎已关闭。我如何实现上述尝试?

2 个答案:

答案 0 :(得分:1)

你不需要case stmt。

    WHERE DTH.PointPerson LIKE @userParam
        AND ActivityDate >= @startDateParam
        AND ActivityDate <= @endDateParam
        AND (
            (@orgTeamPK = '%' AND (USR.[OrganizationalTeamId] LIKE @orgTeamPK OR USR.[OrganizationalTeamId] IS NULL) )
            OR
            (@orgTeamPK <> '%' AND (USR.[OrganizationalTeamId] LIKE @orgTeamPK ) )

答案 1 :(得分:1)

正如@Anup所提到的,你不需要一个案例陈述,但imho使用案例使语法更清晰......   where子句中的每个部分必须是&#34; PREDICATE&#34;,即它必须求值为布尔值。 where子句中的case语句不会计算为布尔值。要修复,请按如下所示进行更改:

 WHERE DTH.PointPerson LIKE @userParam
   AND ActivityDate >= @startDateParam
   AND ActivityDate <= @endDateParam

   --new section below
   AND USR.OrganizationalTeamId Like 
        CASE (@orgTeamPK) WHEN '%' THEN coalesce(@orgTeamPK, USR.OrganizationalTeamId)
              ELSE @orgTeamPK end