当我尝试通过Trigger删除数据时,它正在删除整个表的数据-不仅是Where子句。
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
答案 0 :(得分:0)
在您的第一个触发器中,您无需出于需要而在DELETE上触发。因为您要针对特定条件进行删除,但是如果已经删除,则无需触发它即可删除。 而且您应该考虑使用散装插入物,扳机应将其覆盖。我简化了您的第一个触发器。 顺便说一句,如果我想忽略表上的某些插入记录,则我更喜欢 INSTEAD OF INSERT 触发器。
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