2013-06-26 70 views
0

我正在寫下面的代碼。將過程IN參數與cusrsor值進行比較。將過程參數與光標值進行比較

create or replace procedure dashboard_addtion(customer_name IN varchar2) 
IS 
num number:=0; 
CURSOR cname_cur 
    IS Select customername from customer_master; 
cname varchar2(300); 
begin 
    for cname in cname_cur loop 
     if upper(cname.customername)!=upper(customer_name) then 
      num:=num+1; 
     end if; 
    end loop; 
    if num != 0 then 
     insert into customer_master select max(customerid) + 1, customer_name 
     from customer_master; 
    end if; 
end; 

它一直在執行它的INSERT語句。

+0

標題似乎與問題沒有關係,但我不完全確定問題是什麼。您正在循環所有現有記錄並計算那些與您的參數不匹配的記錄;如果*任何*不匹配,那麼你插入一個新的記錄。只有當匹配參數的參數不存在時,才真的試圖插入新記錄嗎?你不需要光標。 –

+0

@AlexPoole:是的亞歷克斯我想插入新紀錄,只有當它已經不存在。 – user2523846

+0

@AlexPoole:是的,我知道它可能沒有使用光標。但是我只想清晰地瞭解遊標如何工作,請建議TY :) – user2523846

回答

0

在您明確要使用遊標進行實驗的基礎......你似乎有對num增量的邏輯和向後檢查:

for cname in cname_cur loop 
    if upper(cname.customername) = upper(customer_name) then 
    num := num+1; 
    end if; 
end loop; 
if num = 0 then 
    insert into customer_master 
    select max(customerid)+1,customer_name from customer_master; 
end if; 

這將計算光標記錄了符合您參數,並且只有在找到時才執行插入操作。

這可能是更清晰的使用boolean標誌:

... is 
    found boolean := false; 
    cursor cname_cur is select custname from customer_master; 
begin 
    for cname in cname_cur loop 
    if upper(cname.customername) = upper(customer_name) then 
     found := true; 
    end if; 
    end loop; 
    if not found then 
    insert into customer_master 
    select max(customerid)+1,customer_name from customer_master; 
    end if; 
end; 

還要注意的是,你不需要申報cname明確;它被重新聲明爲for ... in ... loop語法的一部分。

+0

謝謝,我可能需要您的更多幫助才能熟悉PL/SQL :) – user2523846