PL / SQL嵌套循环(循环内循环)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PL / SQL嵌套循环(循环内循环)相关的知识,希望对你有一定的参考价值。
下面是我正在研究的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的帮助将不胜感激
答案
在打印语句后,您没有清除缓冲区,因此您将下一个语句附加到第一个语句。要清除缓冲区,请添加
v_sql := NULL;
在阅读之后
dbms_output.put_line(v_sql);
祝你好运。
另一答案
内部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>
以上是关于PL / SQL嵌套循环(循环内循环)的主要内容,如果未能解决你的问题,请参考以下文章
创建在循环内输出不同名称的 Oracle PL/SQL 过程