1

我正在尝试调用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 吗?

4

2 回答 2

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 
于 2013-08-18T17:54:38.337 回答
1

0..N触发器可以为已删除的行触发。例如:

delete  YourTable
where   1=2

for deleteYourTable. 因此触发器必须能够处理零行或多行。考虑重写您的触发器,例如:

ALTER TRIGGER [audit] ON [dbo].[S_PARTY] FOR DELETE
AS
INSERT  dbo.S_AMF_AUDIT_ITEM
        (ROW_ID)   
SELECT  ROW_ID
FROM    deleted

这将适用于任意数量的插入行。

于 2013-08-18T17:55:32.077 回答