当我在查询中发现多个结果时,我想继续 Oracle sql 循环 - 所以我的简化代码:
declare
cursor foo_cursor select * from foo_table;
foo foo_cursor%ROWTYPE;
begin
open foo_cursor;
loop
fetch foo_cursor into foo;
exit when foo_cursor%NOTFOUND;
continue when ( -- the next query has entries or an entry,
-- but how do I do this?
select count(*) from bar_table where bar_column=foo.foo_column
group by bar_column having count(1)>1;
)
insert into uninterresting_table (some_column) VALUES
(foo.foo_column);
end loop;
close foo_cursor;
end;
最佳答案
看来您只想对 FOO_TABLE
中的记录进行操作当 BAR_TABLE
中至少存在两条相关记录时。您可以更改 foo_cursor
的定义如下所示考虑该要求。这样您就不需要反复检查 BAR_TABLE
中是否存在记录。每次。
declare
cursor foo_cursor is
select *
from foo_table foo
where exists (select 1 from bar_table bar
where bar.bar_column = foo.foo_column
having count(*) > 1);
foo foo_cursor%ROWTYPE;
begin
open foo_cursor;
loop
fetch foo_cursor into foo;
exit when foo_cursor%NOTFOUND;
insert into uninteresting_table (some_column) VALUES
(foo.foo_column);
end loop;
close foo_cursor;
end;
/
另一方面,如果您想跳过 FOO_TABLE
中的记录BAR_TABLE
中已有两条或更多记录,您可以反转存在检查,其他一切都一样:
declare
cursor foo_cursor is
select *
from foo_table foo
where NOT exists (select 1 from bar_table bar
where bar.bar_column = foo.foo_column
having count(*) > 1);
foo foo_cursor%ROWTYPE;
begin
open foo_cursor;
loop
fetch foo_cursor into foo;
exit when foo_cursor%NOTFOUND;
insert into uninteresting_table (some_column) VALUES
(foo.foo_column);
end loop;
close foo_cursor;
end;
/
如果要处理FOO_TABLE
中的所有记录但当 BAR_TABLE
中存在两个或多个记录时执行其他操作,您仍然可以通过更改 foo_cursor
来做到这一点:
declare
cursor foo_cursor is
select foo.*
, case when exists (select 1 from bar_table bar
where bar.bar_column = foo.foo_column
having count(*) > 1)
then 'Y'
else 'N'
end has_two_or_more
from foo_table foo;
foo foo_cursor%ROWTYPE;
begin
open foo_cursor;
loop
fetch foo_cursor into foo;
exit when foo_cursor%NOTFOUND;
continue when foo.has_two_or_more = 'Y';
insert into uninteresting_table (some_column) VALUES
(foo.foo_column);
end loop;
close foo_cursor;
end;
/
关于sql - 如何在循环中使用 select in continue when 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54352457/