简体   繁体   中英

trigger if else

I have a trigger that verifies if a field is null:

create or replace trigger trig1
after insert on table_1
for each row
begin
if ((select table2.column2 from table2 where table2.id= :new.id) isnull) then
update table2 set table2.column2 = :new.column1 where table2.id = :new.id;
end if;
end trig1;
.
run;

I get an error that the trigger is created with compilation errors. I don't know what the problem is. I use Oracle SQL*Plus 10.2.0

The PL/SQL syntax doesn't allow for including SQL statements in the IF clause.

The correct approach is to separate out the SELECT statement and then test for its result. So that would be:

create or replace trigger trig1 
after insert on table_1 
for each row 
declare
    v table2.column2%type;
begin
    select table2.column2 
    into v
    from table2 
    where table2.id= :new.id;

    if v is null
    then 
        update table2 
        set table2.column2 = :new.column1 
        where table2.id = :new.id; 
    end if; 
end trig1;

Note that this does not handle the existence of multiple rows in table2 matching the criteria, or indeed there being no matching rows. It also doesn't handle locking.

Also, bear in mind that code like this doesn't function well in multi-user environments. That's why I mentioned locking. You ought really to use procedural logic to handle these sorts of requirements. Although as is often the case with ill-conceived triggers the real culprit is a poor data model. table2.column2 should have been normalised out of existence.

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