如何在游标的select语句where子句中传递逗号分隔的值

时间:2019-02-20 09:38:46

标签: sql oracle plsql

我有以下具有光标和选择查询的块。我想传递选择的输出,以逗号分隔成 游标的select语句,进入where子句。 我知道下面的代码会由于“声明”部分中的SQL查询而引发错误,但是我如何使用数组或集合来实现此目的。

此处,id列为数字

代码段:

declare
test varchar2(30);
SELECT LISTAGG(value, ', ') WITHIN GROUP (ORDER BY value2) into test from table3 where value2=12;
cursor c1 (select * from table where id in (test))
begin
for i in c1 loop
null;
end loop;
end;

2 个答案:

答案 0 :(得分:3)

你为什么要这么做?

您可以简单地将选择写为:

Select * from table where id in (select value from table3 where value2=12)

编辑:

此外,您还需要打开光标c1才能使AFAIK工作。

答案 1 :(得分:2)

您可以使用集合和MEMBER OF运算符:

Oracle设置

CREATE TYPE IntegerList  AS TABLE OF NUMBER(8,0);
/

CREATE TABLE table1 ( value, value2 ) AS
SELECT 1, 1 FROM DUAL UNION ALL
SELECT 3, 4 FROM DUAL UNION ALL
SELECT 5, 3 FROM DUAL UNION ALL
SELECT 7, 2 FROM DUAL;

CREATE TABLE table2 ( id, value ) AS
SELECT 1, 11 FROM DUAL UNION ALL
SELECT 2, 22 FROM DUAL UNION ALL
SELECT 3, 33 FROM DUAL UNION ALL
SELECT 7, 77 FROM DUAL;

PL / SQL

DECLARE
  test IntegerList;
  c1 SYS_REFCURSOR;
BEGIN
  SELECT value
  BULK COLLECT INTO test
  FROM   table1;

  FOR r IN ( SELECT * FROM table2 WHERE id MEMBER OF test ) LOOP
    DBMS_OUTPUT.PUT_LINE( r.id || ', ' || r.value );
  END LOOP;
END;
/

输出

1, 11
3, 33
7, 77

db <>提琴here