2017-01-06 48 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  
相關問題