4

我想将一个数字列表查询到一个 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;
4

1 回答 1

4

使用 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

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

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

  8    select user_id
  9    bulk collect into v_ids
 10    from user_users;

如果您的数组最终可以包含数千行或更多行,通常情况并不好,因为您对内存施加了太大的压力并最终会使代码崩溃。最好使用显式游标open x for ..和循环中的大容量获取以及限制子句,即fetch x bulk collect into v_ids limit 100分批处理 100-1000。

于 2012-11-29T15:03:33.100 回答