Oracle:如何使用启用/禁用WHERE条件编写查询

时间:2013-07-18 11:13:12

标签: sql oracle

我已经通过这种方式来实现可参数化的查询。 你知道任何变种吗?

WITH temp AS (SELECT 'case1' case FROM DUAL)
SELECT 1
  FROM temp
 WHERE    (    (1 = DECODE (case, 'case1', 1, 0))
           AND SYSDATE > TO_DATE ('01/01/2013', 'DD/MM/YYYY'))
       OR (    (1 = DECODE (case, 'case2', 1, 0))
           AND SYSDATE < TO_DATE ('01/01/2013', 'DD/MM/YYYY'))

3 个答案:

答案 0 :(得分:3)

你可以使用案例

WITH temp AS (SELECT 'case1' _case FROM DUAL)
SELECT 1
  FROM temp
 WHERE   
 1 = case
      when _case = 'case1'
      AND SYSDATE > TO_DATE ('01/01/2013', 'DD/MM/YYYY')
      then 1
      when _case = 'case2'
      AND SYSDATE > TO_DATE ('01/01/2013', 'DD/MM/YYYY')
      then 1
      else 0
     end 
; 

答案 1 :(得分:2)

这看起来很尴尬。您只需使用基本逻辑即可完成此操作:

WITH temp AS (SELECT 'case1' case FROM DUAL)
SELECT 1
FROM temp
WHERE ((case = 'case1') and SYSDATE > TO_DATE('01/01/2013', 'DD/MM/YYYY')) or
      ((case = 'case2') and SYSDATE < TO_DATE('01/01/2013', 'DD/MM/YYYY'))

答案 2 :(得分:0)

为什么不使用功能:

 CREATE FUNCTION x ( p_case IN VARCHAR2, p_date IN VARCHAR2 )
 RETURN INTEGER
 IS
 BEGIN
      IF p_case = 'case1' AND TO_DATE(p_date, 'DD/MM/YYYY') < SYSDATE THEN RETURN 1;
      ELSE IF p_case = 'case2' AND TO_DATE(p_date, 'DD/MM/YYYY') < SYSDATE THEN RETURN 1;
      ELSE RETURN 0;
      END IF;
 END;

 SELECT 1 FROM dual WHERE x('case1', '01/01/2013') = 1;