oracle - 在 'IN' 子句中使用绑定(bind)变量

标签 oracle plsql oracle10g bind-variables

我想将数字列表查询到 plsql 变量中,并在另一个 SQL 查询的 in 子句中使用它。我在下面创建了一个我想要做的测试用例。

我在谷歌上搜索了解决方案,我认为它一定有可能,但我就是无法运行它。请帮我解决编译问题。

CREATE OR REPLACE PROCEDURE PROCEDURE1 
as
  type t_id is table of number;
  v_ids t_id;
  v_user_ids number;
BEGIN

-- fill variable v_id with id's, user_id is of type number
select user_id
bulk collect into v_ids
from user_users;

-- then at a later stage ... issue a query using v_id in the in clause
select user_id into v_user_ids from user_users
-- this line does not compile ( local collection type not allowed in SQL statements)
where user_id in ( v_ids );

END PROCEDURE1;

最佳答案

使用 SQL 类型:

SQL> create type t_id is table of number;
  2  /

Type created.

SQL> CREATE OR REPLACE PROCEDURE PROCEDURE1
  2  as
  3    v_ids t_id;
  4    v_user_ids number;
  5  BEGIN
  6
  7    -- fill variable v_id with id's, user_id is of type number
  8    select user_id
  9    bulk collect into v_ids
 10    from user_users
 11    where user_id between 100 and 120;
 12
 13    select user_id into v_user_ids
 14      from user_users
 15     where user_id in (select /*+ cardinality(t, 10) */ t.column_value from table(v_ids) t)
 16       and rownum = 1;
 17
 18    dbms_output.put_line(v_user_ids);
 19
 20  END PROCEDURE1;
 21  /

Procedure created.

SQL> exec procedure1
100

其中 cardinality(t, 10) 应该是对数组中有多少元素的合理猜测。

注意: 像您一样使用无限制的批量收集:

  8    select user_id
  9    bulk collect into v_ids
 10    from user_users;
如果您的数组最终可能有数千行或更多行,那么通常情况不太好,因为您对内存施加了太大的压力,最终会使代码崩溃。您最好使用显式游标 open x for .. 和带有 limit 子句的循环中的批量获取,即 fetch xbulkcollect into v_ids limit 100 和批量处理,例如 100-1000 个。

关于oracle - 在 'IN' 子句中使用绑定(bind)变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13627493/

相关文章:

c++ - 在 C++ 中连接到 sql?

java - SQL从至少有一个异性的表中获取前3名

java - Weblogic 12c 与 Oracle 数据库 18c : setTransactionOnly() called on transaction error

sql - FORALL 与 FOR 批量更新

sql - 以另一个用户身份执行 Oracle 存储过程

sql - Oracle SQL - 仅当某个条件为真时才可以连接两个表吗?

oracle10g - 有人可以帮我解决 Oracle (10g) AND/OR 短路问题吗?

oracle - OCIEnvCreate 失败,返回代码 -1,但错误消息文本在 ODP.net 中不可用

sql - 在 Oracle SQL 中查找不唯一的行

sql - 返回 varchar2/numbers 的 PL/SQL 函数