我在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'中的值賦值爲標量變量總是一個錯誤,因爲它忽略了*這些其他行。 –