插入触发器重复记录不能正常工作的SQL Server

时间:2015-01-24 12:15:22

标签: sql-server triggers 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

在insert语句中没有触发触发器,但是如果我删除变量并填充数据并在SQL Server上运行它运行正常。

有什么建议吗?

如果我将行(@counter >= 1)更改为(@counter >= 0),则会再次开始工作。

2 个答案:

答案 0 :(得分:0)

如果插入多行,“插入”中会有多行,但您只检查最后一行。制作检查约束可能更容易,具体取决于关于“sth_evraktip = 6”的规则实际上是什么(稍后可以通过更新来完成更多行等)。

使用插入触发器可能会起作用:

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

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

答案 1 :(得分:-1)

如果我跳过变量声明并且传递给变量触发器的值可以完美地工作。在我的情况下对于每一行 编辑的代码发布在下面。

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