CREATE TRIGGER TriInsertCaiGouZhuBiao ON [dbo].[tb_caiGouZhuBiao] 
FOR INSERT
AS
begin
  declare @danHao varchar(100);
  select @danHao=caiGouDanHao from inserted;
  declare @count int;
  select @count=count(AutoID) from tb_caiGouZhuBiao where caiGouDanHao=@danHao;
  if(@count>0)
    begin
      rollback;
    end
  else
    begin
      commit;
    end
end
以上我是写的一个添加的触发器
我就是想当插入的信息要是已经存在的话,就不添加,否则就添加
但是为什么我在添加的时候,什么都添加不了呢?
哪位知道我错在哪里,帮我解决下,谢谢

解决方案 »

  1.   

    CREATE TRIGGER TriInsertCaiGouZhuBiao ON [dbo].[tb_caiGouZhuBiao] instead of INSERT
    AS
    begin
    insert into tb_caiGouZhuBiao select * from inserted a
    where not exists(select 1 from tb_caiGouZhuBiao where caiGouDanHao=a.caiGouDanHao)
    end
      

  2.   

    CREATE TRIGGER TriInsertCaiGouZhuBiao ON [dbo].[tb_caiGouZhuBiao] 
    instead of  INSERT
    AS
    begin
    if not exists (select * from inserted i join tb_caiGouZhuBiao  k on i.caiGouDanHao=k.caiGouDanHao)
    begin 
    insert tb_caiGouZhuBiao
    select * from inserted 
    end
    else 
    print '已经存在'
     
    end
      

  3.   

    create trigger TriInsertCaiGouZhuBiao ON [dbo].[tb_caiGouZhuBiao] 
    instead of INSERT
    as
    begin
        insert into tb_caiGouZhuBiao select * from inserted a
        where not exists(select 1 from tb_caiGouZhuBiao where caiGouDanHao=a.caiGouDanHao)
    end
      

  4.   

    --按照楼主的意思 写INSERT触发器也可以的CREATE TRIGGER TriInsertCaiGouZhuBiao ON [dbo].[tb_caiGouZhuBiao] 
    FOR INSERT
    AS
    begin
      if (select count(*) from inserted i join tb_caiGouZhuBiao t on i.caiGouDanHao=caiGouDanHao)>1
      begin
          rollback;
        end
      else
        begin
          commit;
        end
      end