删除SQL Server中的虚拟表为空ON删除触发器

时间:2013-08-18 17:33:26

标签: sql sql-server sql-server-2005

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

2 个答案:

答案 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

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