rad*_*nys 1 sql oracle collections plsql
我希望有一个嵌套表来保存自定义对象,通过从多个游标逐个添加它们.但我不想在表格中有重复.我怎样才能做到这一点?
以下是我向表中添加元素的方法:
create type recipient as object (firstname varchar2, lastname varchar2, email varchar2);
declare type recipients_list is table of recipient;
rec recipients_list := recipients_list();
cursor admins is
select firstname, lastname, email
from users
where profile_id = 1;
cursor operators is
select firstname, lastname, email
from users
where operator = 1;
-- an user may be both admin and operator
....
for to_email in admins
loop
rec.extend;
rec(rec.last) := recipient(to_email.firstname, to_email.lastname, to_email.email);
end loop;
for to_email in operators
loop
rec.extend;
rec(rec.last) := recipient(to_email.firstname, to_email.lastname, to_email.email);
end loop;
Run Code Online (Sandbox Code Playgroud)
请注意,这只是一个示例,在这种特殊情况下,可以更改选择以便只有一个游标.但在我的申请中,情况有所不同.谢谢!
如果您使用的是Oracle 10g或更高版本,则有几种简单的方法可以解决此问题.
一种是使用现有代码,在OPERATORS循环中使用MEMBER OF运算符来测试它是否已存在于集合中.
但是,更简单的方法是定义三个集合.使用批量收集使用每个查询中的完整记录集填充两个集合,然后使用第三个集合过滤掉任何重复项.
像这样的东西:
declare
type recipients_list is table of recipient;
recs recipients_list := recipients_list();
admins recipients_list := recipients_list();
operators recipients_list := recipients_list();
begin
select firstname, lastname, email
bulk collect into admins
from users
where profile_id = 1;
select firstname, lastname, email
bulk collect into operators
from users
where operator = 1;
recs := admins multiset union distinct operators;
end;
/
Run Code Online (Sandbox Code Playgroud)
"有可能有多个工会吗?"
一定是可能的.我不知道是否有最大值,但如果有最大数量.我发现Oracle中的限制往往是慷慨的; 如果我们发现自己要抵御极限,那么可能有更好的方法来做任何事情.