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

cardinality(t, 10)配列に含まれる要素の数を合理的に推測できる場所はどこですか。

注:次のように無制限の一括収集を使用します。

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

配列に数千以上の行が含まれる可能性がある場合は、メモリに過度のストレスをかけ、最終的にコードをクラッシュさせるため、一般的にはあまり良くありません。明示的なカーソルopen x for ..と、limit句を使用したループでの一括フェッチ、つまりfetch x bulk collect into v_ids limit 100100〜1000のバッチで処理する方が適切です。

于 2012-11-29T15:03:33.100 に答える