我在数据库中有这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在线:
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时尝试异常,但后来又抱怨异常不在正确的地方...
答案 0 :(得分:0)
这应解决问题:
-- 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;