触发执行插入

时间:2012-10-01 07:19:54

标签: sql triggers sqlanywhere

我必须创建一个不允许某个列中有多个null的触发器(hourfinish)。这是我写的触发器(我正在使用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

触发器工作正常。我要问的是,是否有一个命令执行插入 - 一个可以替换那些长插入语句的命令。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

我使用before insert触发器获得了相同的结果。这样我就不需要在触发器中写入任何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