从邮递员推送数据时,sql触发器不起作用

问题描述 投票:-1回答:1

当我试图通过Trigger删除数据时,它正在删除全表的数据 - 不仅仅是Where子句1。

Create TRIGGER trgAfterInsertFDs ON [dbo].MyTable
FOR INSERT,Delete
AS
    declare @id nvarchar(max)
    declare @Status nvarchar(100);

    select @id=i.ID from inserted i;    
    select @Status=i.[Status] from inserted i;  
    Delete from MyTable where ID=@id and [Status]='Closed'
GO

我也试过了其他方式。要将自动生成的ID从“我的表”转储到另一个表,并再写一个触发器以从“我的表”中删除数据。

Create TRIGGER trgAfterInsert ON [dbo].MyTable
FOR INSERT,Delete
AS
    declare @id nvarchar(max)
    declare @Status nvarchar(100);

    select @id=i.ID from inserted i;    
    select @Status=i.[Status] from inserted i;  
    Delete from MyTable where ID=@id and [Status]='Closed'
        Insert into ClosedID
    Select ID,[Status] from [dbo].MyTable where ID=@id and Status='Closed'
GO

表ClosedID:

Create table ClosedID 
  (ID int,Status nvarchar(max))


Create TRIGGER trgAfter ON ClosedID
FOR INSERT
AS
    declare @ID nvarchar(max)
    declare @Status nvarchar(100);

    select @id=i.ID from inserted i;    
    select @Status=i.Status from inserted i;    
    delete from [dbo].MyTable where id in (Select ID from ClosedID)
    --Delete  from ClosedID
GO
sql sql-server tsql triggers
1个回答
0
投票

在第一次触发时,您无需为了您的目的触发DELETE。因为您要删除特定条件但是如果它已被删除,则不需要触发它来删除。你应该考虑批量插入,你的触发器应该覆盖它。我简化了你的第一个触发器。通常,如果我想忽略表上的一些插入记录,我更喜欢INSTEAD OF INSERT Trigger。

CREATE TRIGGER trgAfterInsertFDs ON [dbo].MyTable
FOR INSERT
AS
    DELETE FROM MyTable 
        WHERE EXISTS (SELECT 1 FROM INSERTED I WHERE MyTable.Id=I.Id AND I.[Status]='Closed')
GO
© www.soinside.com 2019 - 2024. All rights reserved.