从另一个表中删除触发器和获取字段

时间:2017-01-06 15:36:15

标签: sql sql-server triggers database-trigger

我在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    

3 个答案:

答案 0 :(得分: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可能包含多行,因此假设它有一行可能会导致运行时错误或结果不正确。
  • 如果状态没有匹配的行,则需要left join
  • 您应始终在insert
  • 中添加列
  • 您的存档表应该有其他列,例如标识列和插入日期,这些列是自动设置的(因此不是显式的插入部分)。

答案 1 :(得分:0)

对于每个语句(删除,插入,更新),触发器将被触发一次,而不是对于语句中的每一行。

您不能在此处使用变量,因为从表中删除多行时,只会在Audit表中插入一行,因为该变量只能包含一个值。

您只需要将已删除表中的一个简单插入到Audit表中,就像这样....

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  

答案 2 :(得分: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