Sql server 为sql server不工作的重复记录插入触发器

Sql server 为sql server不工作的重复记录插入触发器,sql-server,triggers,insert,Sql Server,Triggers,Insert,insert语句不会触发触发器,但是,如果我删除变量并填充数据并在SQL Server上运行,则触发器运行正常 有什么建议吗 还有一件事,如果我将@counter>=1行更改为@counter>=0,它将重新开始工作。如果插入多行,则插入的行将不止一行,但您只检查最后一行。进行检查约束可能更容易,这取决于与sth_evraktip=6相关的规则实际是什么,是否可以在以后的更新中完成更多行等 使用insert触发器时,类似这样的操作可能会起作用: ALTER TRIGGER [dbo].[STOK

insert语句不会触发触发器,但是,如果我删除变量并填充数据并在SQL Server上运行,则触发器运行正常

有什么建议吗


还有一件事,如果我将@counter>=1行更改为@counter>=0,它将重新开始工作。

如果插入多行,则插入的行将不止一行,但您只检查最后一行。进行检查约束可能更容易,这取决于与sth_evraktip=6相关的规则实际是什么,是否可以在以后的更新中完成更多行等

使用insert触发器时,类似这样的操作可能会起作用:

ALTER TRIGGER [dbo].[STOK_HARKETLERI_Insert]    
ON [dbo].[STOK_HAREKETLERI]              
FOR INSERT 
AS BEGIN  
    declare @tip int 
    declare @miktar float 
    declare @stokkod nvarchar 
    declare @tarih datetime 
    declare @counter int  

    Select 
        @tip = sth_tip,  @miktar = sth_miktar,  
        @stokkod = sth_stok_kod, @tarih = sth_tarih 
    from inserted 

    select @Counter = COUNT(sth_tip) 
    from STOK_HAREKETLERI  
    where sth_evraktip = 6 
      and sth_tip = @tip 
      and sth_miktar = @miktar 
      and @stokkod = sth_stok_kod 
      and @tarih = sth_tarih   

    if (@counter>=1)  
    begin     
       rollback     
       RAISERROR ('Record already exists', 17, -1) with log 
    end    
END
GO

如果任何列可以包含NULL,那么您必须添加更多的逻辑来处理它。

如果我跳过变量声明,并且传递给变量触发器的值可以完美地工作 编辑后的代码发布在下面

if exists (select 1 from inserted i
where exists(select 1 from STOK_HAREKETLERI S
where S.sth_evraktip = 6
and S.sth_tip = i.sth_tip
and S.sth_miktar = i.sth_miktar
and S.sth_stok_kod = i.sth_stok_kod
and S.sth_tarih = i.sth_tarih
and S.sth_RECno < i.sth_RECno)) begin
    rollback
    RAISERROR ('Record already exists', 17, -1) with log 
 end

触发器不会对每一行执行,它是在语句级别上。请解释一下您的语句好吗?您的触发器有一个主要缺陷,您似乎认为它每行调用一次—事实并非如此。每个语句触发一次触发器,因此如果UPDATE语句影响25行,则触发一次触发器,但Inserted和Deleted语句将分别包含25行。您的代码将选择这25行中的哪一行?这是不确定的。你需要重写你的触发器来考虑这一点!这类事情不是最好有一个独特的约束吗?@davidaber不,为什么?因为这个表中有很多类型的记录,我不想停止,我只想停止这一个。我试图只插入一行,但失败了。失败是什么意思?你有错误还是检查不起作用?不,它没有给出错误,这是我的朋友的问题。添加了一个应该起作用的示例,但是sth_evraktip和sth_RECno值可能会导致它遗漏一些内容,空值总是需要注意的。谢谢你的建议,我也会尝试这个。
Create TRIGGER [dbo].[STOK_HARKETLERI_Insert]
   ON  [dbo].[STOK_HAREKETLERI]
    FOR INSERT
AS
BEGIN
Declare @counter int

select @counter =  COUNT(sth_tip) from STOK_HAREKETLERI
where sth_evraktip = 6
and sth_tip = (select sth_tip from inserted i)
and sth_miktar =(select sth_miktar from inserted)
and sth_stok_kod =(select sth_stok_kod from inserted)
and sth_tarih = (select sth_tarih from inserted)
and sth_RECno < (select sth_RECno from inserted)

if (@counter>=1)

begin
    rollback
    RAISERROR ('Record already exists', 17, -1) with log
end


END