2015-04-04 57 views
-1

我有表和順序:「SELECT COUNT(*)」返回不同的結果和PL/SQL程序外

create table sometable (
    id number(10) not null, 
    application varchar2(255 char) not null, 
    constraint sometable_pk primary key (id) 
); 

create sequence sometable_seq minvalue 1 start with 1 increment by 1 cache 10; 

和PL/SQL過程,假設你插入到表中,但第一次檢查,如果這樣的條目已經存在並拋出定製ORA-20000錯誤,如果是這樣的話:

create or replace 
procedure dosth 
(
    application in varchar2 
) 
is 
    l_cnt integer := 0; 
begin 
    select count(*) into l_cnt from sometable s where s.application = application; 
    dbms_output.put_line('count ' || l_cnt); 
    if (l_cnt = 0) then 
    insert into sometable (id, application) values (sometable_seq.nextval, application); 
    else 
    raise_application_error(-20000, 'application already exist:' || application); 
    end if; 
end dosth; 
/

當我打電話PL/SQL:

begin 
    dosth('app1'); 
end; 
/

我收到:

anonymous block completed 
count 0 

所有確定,因爲表中沒有這樣的條目。用相同的參數第二次調用預期:

ORA-20000: application already exist:app1 
count 1 

但令人奇怪的是,使用不同的參數值連續調用導致同樣的錯誤。

begin 
    dosth('app2'); 
end; 
/
ORA-20000: application already exist:app2 
count 1 

當然有在表中沒有該項

select count(*) from sometable s where s.application = 'app2'; 

返回0而不是1爲PL/SQL程序裏面!

這真的很讓人困惑..可能真的很愚蠢。請幫忙。

+1

在條件使用過程名稱:'...其中s.application = DOSTH.application'或使用唯一約束,就像@Mat說。 – 2015-04-04 10:52:28

+0

Thx提示。我不想使用唯一的約束,因爲我需要自定義的ORA-20000錯誤。這只是一個更復雜的代碼樣本,以縮小我的問題範圍。我會嘗試重命名參數或使用過程名稱,但..這仍然是令人困惑的,我不明白爲什麼它的工作原理。 – GrzegorzM 2015-04-04 11:01:18

+3

它不工作,因爲你檢查這個像'where application = application'。計數返回所有行的數量。 – 2015-04-04 11:04:59

回答

0

謝謝你們。要解決它,你指出我不得不改變這一行:

select count(*) into l_cnt from sometable s where s.application = application; 

select count(*) into l_cnt from sometable s where s.application = dosth.application; 

雖然它是反直覺的(在列表對我來說)看來,這是這樣的PL/SQL工程。

相關問題