删除触发器不起作用

时间:2013-03-09 07:21:12

标签: sql-server tsql triggers

我创建了一个简单的删除触发器,它被触发但0行受影响。父表记录已删除。但是记录中的表也应该删除不删除。我有以下查询。

ALTER trigger [dbo].[studentAuditActionDelete] on [dbo].[tblStudent]

after delete
AS

declare @studentId_Audit int;

    select @studentId_Audit = i.studentID from inserted i;  
    delete from studentAudit
    where
    studentId_Audit = @studentId_Audit
    PRINT 'AFTER Delete trigger fired.'

2 个答案:

答案 0 :(得分:3)

您是否尝试过从deleted

中进行选择
select @studentId_Audit = d.studentID from deleted d;

请记住,deleted可以包含多行,您只需选择其中一行! (这是为了让所有触发器都能记住insertedupdateddeleted

答案 1 :(得分:0)

不要在触发器中声明变量,使用简单的JOIN与源表DELETED并且您将能够使用多个删除

CREATE TRIGGER [dbo].[studentAuditActionDelete] on [dbo].[tblStudent]
FOR DELETE
AS
  DELETE a
  FROM studentAudit a JOIN deleted d ON a.studentId_Audit = d.studentID  
  PRINT 'AFTER Delete trigger fired.'