2017-01-06 40 views
0

我在SQL数据库上有此删除触发器。该记录将当前删除并写入审计表。我被要求在这个历史表中包含另一个与根据SurveyID删除的记录相关的表中的字段。我以为我可以做类似删除触发器并从另一个表中获取字段

select @Status = Status from table where Survey = deleted.Survey 

但是这是不正确的语法。

ALTER trigger [dbo].[table_Selfdelete] 
on [dbo].[table] 

after delete 
as 
Begin 
Set nocount on; 

Declare @SurveyId int 
Declare @StudentUIC varchar(10) 
Declare @Status varchar(10) 

select @SurveyId = deleted.SurveyID, 
     @StudentUIC = deleted.StudentUIC 
from deleted 

select @Status = Status from tbly when SurveyID = deleted.SurveyID 

insert into fupSurveyAudit 
    values(@SurveyId,@StudentUIC,@Status) 


End  
+0

如果删除多行,该怎么办? – DVT

+2

到目前为止发布的三个答案都没有强调DVT暗示的重要观点(但他们都确实解决了这个问题)。触发器每个*语句*触发一次,因此'deleted'可以包含0,1或*多个*行。正如你在这里所做的那样,将'deleted'中的值赋值为标量变量总是一个错误,因为它忽略了*这些其他行。 –

回答

1

Arrgh。我想你想这insert在你的触发器(没有别的):

insert into fupSurveyAudit(SurveyId, StudentUIC, status) 
    select d.SurveyId, d.StudentUIC, y.status 
    from deleted d left join 
     tbly y 
     on d.SurveyId = y.SurveyId; 

注:

  • deleted可以包含多个行,所以假设它有一个行会导致运行时间错误或不正确的结果。
  • 如果没有匹配的状态行,则需要A left join
  • 你应该总是包含在insert
  • 你的存档表中的列应该有额外的列,如标识列和插入的日期,这是自动设置的(因此不是插入的明确的一部分)。
0

针对每条语句(删除,插入,更新)的触发器不会针对语句中的每一行触发一次。

您不能在这里使用变量,因为当从表中删除多行时,只有一行将被插入到审计表中,因为该变量只能保存一个值。

你只需从已删除的表的简单插入到审计表是这样的....

ALTER trigger [dbo].[table_Selfdelete] 
on [dbo].[table] 

after delete 
as 
Begin 
Set nocount on; 

insert into fupSurveyAudit(SurveyId, StudentUIC,[Status]) 
select d.SurveyID 
     ,d.StudentUIC 
     ,y.[Status] 
from deleted d 
INNER JOIN tbly y ON y.SurveyID = deleted.SurveyID 

End 
0

试试这个

ALTER trigger [dbo].[table_Selfdelete] 
on [dbo].[table] 

after delete 
as 
Begin 
Set nocount on; 

insert into fupSurveyAudit -- Better listed the column list here 
select 
    d.SurveyID, d.StudentUIC, y.Status 
from 
    deleted d JOIN tbly y ON d.SurveyID = y.SurveyID 

End  
相关问题