我正在尝试调用ON Delete
触发器事件,但是当我尝试从Deleted
表中选择行时,它是空的。
有没有其他方法可以获取已触发删除事件的行的ID?
代码:
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
ALTER TRIGGER [audit]
ON [dbo].[S_PARTY]
FOR DELETE
AS
-- Insert statements for trigger here
DECLARE @id nvarchar(50)
SET @id = (Select ROW_ID from deleted )
BEGIN
-- Insert statements for trigger here
INSERT INTO [dbo].[S_AMF_AUDIT_ITEM] (ROW_ID)
VALUES (@id);
END
当触发器触发时,我收到错误,因为S_AMF_AUDIT_ITEM
不允许空值。所以,请你帮我这个获取删除命令执行的表的Id?
答案 0 :(得分:2)
你的触发器坏了。
它没有考虑DELETE
语句可能会影响零行或多行。
NULL
语句可能会出现DELETE FROM [dbo].[S_PARTY] WHERE 1 = 0
的问题。
固定版本将是
ALTER TRIGGER [audit]
ON [dbo].[S_PARTY]
FOR DELETE
AS
BEGIN
INSERT INTO [dbo].[S_AMF_AUDIT_ITEM]
(ROW_ID)
SELECT ROW_ID
FROM deleted;
END
答案 1 :(得分:1)
触发器可以触发0..N
个已删除的行。例如:
delete YourTable
where 1=2
会在for delete
上运行YourTable
触发器。因此触发器必须能够处理零行或多行。考虑重写你的触发器,如:
ALTER TRIGGER [audit] ON [dbo].[S_PARTY] FOR DELETE
AS
INSERT dbo.S_AMF_AUDIT_ITEM
(ROW_ID)
SELECT ROW_ID
FROM deleted
这适用于任意数量的插入行。