简体   繁体   中英

PL/SQL trigger to insert next value

I created a trigger which works like when I update/insert a row in one table, an insert of a row will a done in another table which contains a primary key. Now when I insert a row in the first table I want the trigger to check the last value of primary key of another table and if that is null or '-' then I've to insert 1 into that primary key column so as to insert the remaining values.

I've written the code as follows:

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;

How to find the last b_id in the vehicles table, so that if that value is null or '-' insert b_id as 1, followed by the above insert statement in the same row.

By adding another trigger we can do that as follows:

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;​

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM