我在数据库中有以下3个表:-人员-事物-类别
“类别”表是新的,因此我必须编写脚本来迁移数据。以前一个人可以有很多东西...现在一个人可以有很多类别,每个类别可以有很多东西。
因此,我必须编写一个遍历事物的脚本,并检查是否已经为事物和人创建了一个组,如果尚未创建一个组,则创建它并更新事物数据。如果已经创建了类别,则只需更新事物数据。
declare
-- thing
v_thing_id thing.id%TYPE;
v_thing_person_id thing.person_id%TYPE;
v_thing_category_name thing.category_name%TYPE;
v_thing_category_id thing.category_id%TYPE;
-- category_name
v_category_id category.id%TYPE;
cursor c_thing_ids is
select b.id
from thing b
where category_id is null
;
begin
open c_thing_ids;
loop
-- iterate all the thing ids
fetch c_thing_ids into v_thing_id;
exit when c_thing_ids%NOTFOUND;
-- look for already created category for current thing
select e.id
into v_category_name_id
from category e
where e.person_id = v_thing_person_id
and e.category_name = v_thing_category_name;
-- if exists: update thing
if v_category_name_id is not null then
update thing
set category_id = v_category_name_id
where id = v_thing_id;
else
-- if not: create category and update thing
insert into category (id, category_name)
values (HIBERNATE_SEQUENCE.NEXTVAL, v_thing_category_name);
select e.id
into v_category_name_id
from category e
where e.person_id = v_thing_person_id
and e.category_name = v_thing_category_name;
update thing
set category_id = v_category_name_id
where id = v_thing_id;
end if;
end loop;
end;
我不是PL / SQL专家,实际上,这是我在“现实生活中”使用它的第二件事,因此,正如预期的那样,我得到一个错误:ORA-01403 in line:
select e.id
into v_category_name_id
from category e
where e.person_id = v_thing_person_id
and e.category_name = v_thing_category_name;
我该如何处理?我在no_data_found时尝试了异常,但是它抱怨异常不在正确的位置...
这应该可以解决问题:
-- look for already created category for current thing
begin
select e.id
into v_category_name_id
from category e
where e.person_id = v_thing_person_id
and e.category_name = v_thing_category_name;
exception when no_data_found then
v_category_name_id := null;
end;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句