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