我在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 :(得分: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