PL / SQL嵌套循环(循环内循环)

问题描述 投票:0回答:2

下面是我正在研究的PL / SQL

declare
v_sql varchar2(500);
BEGIN
for t in (
    SELECT distinct ID 
    FROM TABLEB
    ) loop
    for c in (
        select * from (
            select 'delete from ' as test 
                from  dual
            union all
            select 'TABLEA'||' where ' as test 
                from dual
            union all
            select 'ID='||t.ID 
                from dual
            )
        ) loop
        v_sql := v_sql || c.test;
        end loop;
    dbms_output.put_line(v_sql);
    end loop; 
END;
/

我得到的结果就是这个

delete from TABLEA where ID=1
delete from TABLEA where ID=1delete from TABLEA where ID=2

我想要

delete from TABLEA where ID=1
delete from TABLEA where ID=2

任何PLSQL的帮助将不胜感激

oracle plsql
2个回答
1
投票

在打印语句后,您没有清除缓冲区,因此您将下一个语句附加到第一个语句。要清除缓冲区,请添加

v_sql := NULL;

在阅读之后

dbms_output.put_line(v_sql);

祝你好运。


2
投票

内部FOR循环的目的是什么?它什么都不需要循环,可以简单地重写如下:

declare
  v_sql varchar2(500);
begin
  for t in (select distinct id from tableb) loop
    v_sql := 'delete from tablea where id = ' || t.id ||';';
    dbms_output.put_line(v_sql);
  end loop; 
end;
/

顺便说一句,似乎你错过了v_sql := ...行中的终止分号

人力资源部门表的演示:

SQL> declare
  2    v_sql varchar2(500);
  3  begin
  4    for t in (select distinct department_id id from departments) loop
  5      v_sql := 'delete from tablea where id = ' || t.id ||';';
  6      dbms_output.put_line(v_sql);
  7    end loop;
  8  end;
  9  /
delete from tablea where id = 10;
delete from tablea where id = 20;
delete from tablea where id = 30;
delete from tablea where id = 40;
delete from tablea where id = 50;
delete from tablea where id = 60;
<snip>
© www.soinside.com 2019 - 2024. All rights reserved.