如何根据参数使 WHERE 子句中的谓词可选

How to Make the Predicate in WHERE Clause Optional Based on a Parameter

我有一个 SQL 需要在 WHERE 子句中使用或不使用 condition/predicate 来执行。如果某个值被传递到 PL/SQL 存储过程,这个谓词恰好是一个需要包含在 WHERE 子句中的子查询:

SELECT /* several columns */
FROM X JOIN Y ON X.A = Y.A
WHERE COL1 = 'a'
  AND COL2 IS NULL
  AND /* Several other predicates */
  AND /* This condition should be included only if a value of parameter is 'G'. If it is 'H', it should NOT consider this condition at all */
     NOT EXISTS (SELECT 1 FROM Z WHERE Z.A = X.A)

我尝试使用 CASE/WHEN/THEN/ELSE 但我无法使用 'H' 选项,例如:

SELECT /* several columns */
FROM X JOIN Y ON X.A = Y.A
WHERE COL1 = 'a'
  AND COL2 IS NULL
  AND (CASE
           WHEN 'G' = P_SP_PARAM AND
               NOT EXISTS (SELECT 1
                           FROM Z
                           WHERE Z.A = X.A)
           THEN 1
           WHEN 'H' = P_SP_PARAM 
           THEN 0
        ELSE 0
        END) = 1

你可以这样做:

AND
(P_SP_PARAM <> 'G' OR
 NOT EXISTS (SELECT 1 FROM Z WHERE Z.A = X.A)
)

如果您特别希望它 H,那么:

AND
(P_SP_PARAM = 'H' OR
 NOT EXISTS (SELECT 1 FROM Z WHERE Z.A = X.A)
)

这两个版本都假定 P_SP_PARAM 不是 NULL。可以很容易地修改逻辑以考虑到这一点。