Tuesday, February 2, 2016

SQL: 暫停和重開Trigger

在SQLupdate時,有時DB中設定了Trigger,它會自動執行內部的一些操作,例如以下錯誤信息為例子︰
START: UPD.tablename - tablename_update_trg ! Msg 2627, Level 14, State 1, Procedure tablename_update_trg, Line 30 Violation of PRIMARY KEY constraint 'PK_tablename'. Cannot insert duplicate key in object 'dbo.tablename'. The duplicate key value is (1, 160). The statement has been terminated.
可以看出tablename_update_trg第30行想插入一筆資料,但PK重覆了。這種情況需要暫停Trigger來更新︰

暫停某一個trigger︰
DISABLE TRIGGER tablename_update_trg ON tablename;
重啓︰
ENABLE TRIGGER tablename_update_trg ON tablename;
如果想暫停所有trigger,其實不需要一個一個地關,這個語句可以關掉所有trigger︰
sp_msforeachtable 'ALTER TABLE ? DISABLE TRIGGER all' 
 重啓所有trigger︰
sp_msforeachtable 'ALTER TABLE ? ENABLE TRIGGER all'

No comments: