如何使用变量AS a where子句?

时间:2014-01-15 14:55:43

标签: sql oracle oracle11g

我有一个where子句,我必须多次使用。我是Oracle SQL的新手,所以请原谅我的新手错误:)。我已经阅读了这个网站,但找不到答案:(。这里是SQL语句:

    var condition varchar2(100)
    exec :condition := 'column 1 = 1 AND column2 = 2, etc.'

    Select a.content, b.content 
    from
    (Select (DBMS_LOB.SUBSTR(ost_bama_vrij_veld.inhoud,3)) as content
    from table_name
    where category = X AND :condition
    group by (DBMS_LOB.SUBSTR(ost_bama_vrij_veld.inhoud,3))
    ) A
    ,
    (Select (DBMS_LOB.SUBSTR(ost_bama_vrij_veld.inhoud,100)) as content
    from table_name
    where category = Y AND :condition
    group by (DBMS_LOB.SUBSTR(ost_bama_vrij_veld.inhoud,100))) B
    GROUP BY
    a.content, b.content  

内容字段是CLOB字段,遗憾的是所有需要的值都在同一列中。我的查询不起作用。

1 个答案:

答案 0 :(得分:1)

您不能对where子句使用绑定变量,仅针对特定值。如果你在SQL * Plus或SQL Developer(以及其他一些客户端)中运行它,你可以使用替换变量:

define condition = 'column 1 = 1 AND column2 = 2, etc.'

Select a.content, b.content 
from
(Select (DBMS_LOB.SUBSTR(ost_bama_vrij_veld.inhoud,3)) as content
from table_name
where category = X AND &condition
...

从其他地方,包括JDBC和OCI,你需要将条件作为变量并使用它来构建查询字符串,因此它在解析器看到的代码中重复。从PL / SQL,您可以使用动态SQL来实现相同的功能。我不确定为什么只重复条件是一个问题,如果值会改变,则绑定参数。当然有这样的两个条款似乎有点无意义。

但也许您可以从不同的角度处理这个问题,并且无需重复where子句。无论如何,查询表两次可能效率不高。您可以将您的条件作为子查询应用一次,但如果不知道您的索引或条件的选择性,这可能会更糟:

with sub_table as (
  select category, content
  from my_table
  where category in (X, Y)
  and column 1 = 1 AND column2 = 2, etc.
)
Select a.content, b.content 
from
(Select (DBMS_LOB.SUBSTR(ost_bama_vrij_veld.inhoud,3)) as content
from sub_table
where category = X
group by (DBMS_LOB.SUBSTR(ost_bama_vrij_veld.inhoud,3))
) A
,
(Select (DBMS_LOB.SUBSTR(ost_bama_vrij_veld.inhoud,100)) as content
from sub_table
where category = Y
group by (DBMS_LOB.SUBSTR(ost_bama_vrij_veld.inhoud,100))) B
GROUP BY
a.content, b.content  

我不确定分组是什么 - 消除重复?如果你有一个匹配其他条件的X和Y记录,这才真正有意义,不是吗?也许我没有正确地遵循它。

您还可以使用case声明:

select max(content_x), max(content_y)
from (
  select
    case when category = X
      then DBMS_LOB.SUBSTR(ost_bama_vrij_veld.inhoud,3) end as content_x,
    case when category = Y
      then DBMS_LOB.SUBSTR(ost_bama_vrij_veld.inhoud,100) end as content_y,
    from my_table
    where category in (X, Y)
    and column 1 = 1 AND column2 = 2, etc.
)