Question

I want to query a list of numbers into a plsql variable and use that in a in clause in another sql query. I created a testcase below of what I want to do.

I did google for the solution and I think it must be possible somehow but I just don't get it to run. Please help me out with a compiling solution.

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;
Was it helpful?

Solution

using a SQL type:

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

where cardinality(t, 10) should be a reasonable guess on how many elements are in your array.

note: using an unbounded bulk collect like you have:

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

is generally not great if your array can end up with many thousand or more rows, as you're putting too much stress on the memory and will eventually crash the code. You'd be better served with an explicit cursor open x for .. and a bulk fetch in a loop with the limit clause ie fetch x bulk collect into v_ids limit 100 and process in batches of say 100-1000.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top