Oracle过程:创建动态WHERE子句

时间:2014-06-19 14:10:30

标签: sql oracle procedure

我正在创建一个动态的where子句,但它的'在Error(40,51): PL/SQL: ORA-00905: missing keyword报告column_2 in ('x','y','z'),错误仍然存​​在于其他运营商。

select *
from test_table
where column_1 = <Some_value>
  and (case column_2
          when 'A' then
            column_2 in ('x','y','z')
            column_3 in (1, 2)
          when 'B' then
            column_2 in ('p', 'q', 'r')
            column_3 in (2, 3)
          else
            column_2 = 'x'
            column_3 = 1
        end case);

此外,我还需要在非空的参数中添加where条件,类似这样的

where column_1 = <Some_value>
 if (param_value <> null) then
      column_2 = param_value
end if

请建议我如何实现这一愿望。

1 个答案:

答案 0 :(得分:2)

您无法动态地附加&#34;这样的IN条款,但有几种不同的方法可以做到这一点:

where column_1 = <Some_value>
  and (
     (column_2 = 'A' AND
      column_2 in ('x','y','z') AND
      column_3 in (1, 2)) 
  OR (column_2 = 'B' AND
      column_2 in ('p', 'q', 'r') AND
      column_3 in (2, 3))
  OR (column_2 NOT IN ('A','B') AND
      column_2 = 'x'
      column_3 = 1)
      )

where column_1 = <Some_value>
  and (case column_2
          when 'A' then
            (column_2 = 'x' OR column_2 = 'y' OR column_2 = 'z')
            AND
            (column_3 = 1 OR  column_3 = 2)
          when 'B' then
            (column_2 = 'p' OR column_2 = 'q' OR column_2 = 'r')
            AND
            (column_3 = 2 OR  column_3 = 3)
          else
            column_2 = 'x'
            AND
            column_3 = 1
        end case);

或对每个CASE条件和UNION进行seaparate查询。