2012-10-01 194 views
2

我必須創建一個不允許在某個列(hourfinish)中有多個null的觸發器。這是我寫的觸發器(我正在使用Sybase):觸發器執行插入

ALTER TRIGGER "InsertIntoCardDetail" instead of insert on 
DBA.CardDetail 
referencing new as new_name 
for each row 
begin 
    declare @nullCount integer; 
    if(new_name.hourfinish is null) then 
    select COUNT(*) into @nullCount 
     from CardDetail 
     where hourfinish is null; 
    if(@nullCount > 0) then 
     raiserror 99999 'Cannot have Multiple Nulls' 
    else 
     insert into CardDetail(card,hourstart,hourfinish,"work",project,N) 
     values(new_name.card,new_name.hourstart,new_name.hourfinish,new_name."work",new_name.project,new_name.N) 
    end if 
    else 
    insert into CardDetail(card,hourstart,hourfinish,"work",project,N) 
     values(new_name.card,new_name.hourstart,new_name.hourfinish,new_name."work",new_name.project,new_name.N) 
    end if 
end 

觸發器工作正常。我問的是,如果有執行插入的命令 - 一個可以替換那些長插入語句的命令。

+0

如果你不在這些'ELSE'塊中寫任何東西,數據庫引擎是不是繼續進行插入過程? – Vikdor

+0

我不這麼認爲,因爲它不是插入觸發器。 – Rick77

+0

您是否使用sybase-ase,sybase-iq,sybase-Anywhere? – Parado

回答

0

我INSERT觸發器前,用達到同樣的效果。這樣我就不需要在觸發器中寫入任何插入語句。

ALTER TRIGGER "InsertIntoCardDetail" before insert on 
DBA.CardDetail 
referencing new as new_name 
for each row 
begin 
    if(new_name.hourfinish is null) 
    and exists(select 1 
     from CardDetail 
     where hourfinish is null) then 
    raiserror 99999 'Cannot have Multiple Nulls' 
    end if; 
end 
1

請儘量把觸發更改爲:

ALTER TRIGGER "InsertIntoCardDetail" instead of insert on 
DBA.CardDetail 
referencing new as new_name 
for each row 
begin 
    if(new_name.hourfinish is null) then  
    if exists 
    (select 1 
     from CardDetail 
     where hourfinish is null) then 
     raiserror 99999 'Cannot have Multiple Nulls' 
     return 1 
    end if --exists 
    end if--(new_name.hourfinish is null) 

    insert into CardDetail(card,hourstart,hourfinish,"work",project,N) 
    values(new_name.card,new_name.hourstart,new_name.hourfinish,new_name."work",new_name.project,new_name.N) 

end