PL/SQL 触发器插入下一个值

Posted

技术标签:

【中文标题】PL/SQL 触发器插入下一个值【英文标题】:PL/SQL trigger to insert next value 【发布时间】:2013-12-15 13:19:23 【问题描述】:

我创建了一个触发器,它的工作方式类似于当我在一个表中更新/插入一行时,插入一行将在另一个包含主键的表中完成。 现在,当我在第一个表中插入一行时,我希望触发器检查另一个表的主键的最后一个值,如果该值为 null 或“-”,那么我必须在该主键列中插入 1 以便插入剩余的值。

我写的代码如下:

create or replace trigger "T1"
AFTER
insert or update on "buses"
for each row    
begin
-- Here I want to check the V_id on vehicles table, if that is null or '-' then insert V_id as 1 along with the below insert statement.
if :NEW."b_key" is not null then
INSERT INTO vehicles (b_KEY,B_NAME,ADDRESS_1,CITY,STATE,ZIP,PHONE,WEBSITE) VALUES (:new.b_KEY,:new.b_NAME,:new.ADDRESS_1,:new.CITY,:new.STATE,:new.ZIP,:new.PHONE,:new.WEBSITE);
end if; 
end;

如何在vehicles表中找到最后一个b_id,如果那个值为null或'-',则插入b_id为1,然后在同一行中跟上面的insert语句。

【问题讨论】:

主键的值如何为空? 【参考方案1】:

通过添加另一个触发器,我们可以这样做:

create or replace TRIGGER "B_VEHICLES" 
  before insert on "buses"               
    for each row  
 declare b_number number;
begin  
    select max(B_ID) into b_number from Vehicles;

  if :OLD."B_ID" is null and b_number is null then 
    select 1 into :new."B_ID" from dual; 
else select b_number + 1 into :new."B_ID" from dual;
  end if; 

 end;​

【讨论】:

以上是关于PL/SQL 触发器插入下一个值的主要内容,如果未能解决你的问题,请参考以下文章

PL/SQL 触发器练习

pl/sql 触发器完整性约束问题

PL/SQL ORACLE:删除时触发更新

PL/SQL 触发器以防止插入

基于变化表中的值在插入之前触发 PL/SQL 触发器

“如何修复 oracle pl/sql 中的触发器?