2015-04-04 99 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工程。

相关问题