簡體   English   中英

PL / SQL異常循環

[英]PL/SQL exception in loop

我在數據庫中有以下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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM