PL / SQL Oracle:在插入触发器之前访问新值

时间:2012-11-26 21:43:58

标签: plsql triggers oracle11g

面对以下错误:

[Error] PLS-00049 (12: 11): PLS-00049: bad bind variable 'NEW.OPTION_D'

我正在尝试执行以下操作:

create or replace trigger check_option_for_stage
before insert on lot_option
for each row
when (new.stage_id > 0 and new.option_id > 0)
declare 
not_existing_option exception;
num_count number;
begin
    select count(*) into num_count 
    from option_cost os
    where :new.option_id = os.option_id and :new.stage_id = os.stage_id;
    if num_count = 1 then
        DBMS_OUTPUT.PUT_LINE('The option can be applied to the lot at the current stage');
    ELSE
        raise not_existing_option;    
    end if;
exception
    when not_existing_option then
        DBMS_OUTPUT.PUT_LINE('The option is not available on this stage, therefore rejected');
    when others then
        DBMS_OUTPUT.PUT_LINE('Oops!, something went wrong, it needs your attention!');
end;
/

为什么我要面对这个?为什么它是一个坏的绑定变量?我知道我应该可以通过输入:new.whateverthecolumnname

来访问新值

我正在使用Oracle 11g。

我正在玩的桌子的定义

SQL> desc option_cost
 Name                                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 COST                                      NOT NULL NUMBER
 OPTION_ID                                 NOT NULL NUMBER(38)
 STAGE_ID                                  NOT NULL NUMBER(38)

SQL> desc lot_option;
 Name                                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 LOT_ID                                    NOT NULL NUMBER(38)
 OPTION_ID                                 NOT NULL NUMBER(38)
 COST                                      NOT NULL NUMBER
 DATE_CREATED                                       DATE
 STAGE_ID                                  NOT NULL NUMBER(38)

1 个答案:

答案 0 :(得分:3)

option_id(最后是id)还是仅option_d(没有i)? option_id似乎更有意义。假设option_id是正确的,您的SELECT语句中会出现拼写错误,而您错过了i中的id。你想要像

这样的东西
select count(*) 
  into count 
  from option_cost oc
 where :new.option_id = oc.option_id 
   and :new.stage_id = oc.stage_id;

当然,由于count是一个保留字,因此声明一个名为count的局部变量并不是一个好主意。将该变量命名为l_count或使用其他命名约定来识别局部变量并避免使用保留字更为有意义。