追蹤觸發程序的執行
在監控觸發程序時,一個重要的因素是保留其執行紀錄。這能讓你將觸發程序的執行時間與資料庫中發生的任何問題對照起來。
如果時間吻合,就有可能是這個觸發程序造成了問題。
SQL Server 會在 sys.dm_exec_trigger_stats 檢視表中提供目前載入到記憶體中的任何觸發程序之執行資訊。不過,一旦觸發程序從記憶體移除,相關資訊也會從該檢視表移除,因此你會失去觸發程序的執行歷史。
為了克服這個限制,你決定利用 TriggerAudit 資料表,來儲存任何試圖修改 Orders 資料表列的相關資訊,因為有人回報該資料表經常沒有回應。
本練習屬於課程
在 SQL Server 建立與最佳化觸發程序
練習說明
- 修改
PreventOrdersUpdate觸發程序。 - 設定當
Orders資料表中的列被更新時觸發。 - 將觸發程序執行的其他細節寫入
TriggerAudit資料表。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
-- Modify the trigger to add new functionality
___ TRIGGER PreventOrdersUpdate
ON ___
-- Prevent any row changes
INSTEAD OF ___
AS
-- Keep history of trigger executions
INSERT INTO ___ (TriggerName, ExecutionDate)
SELECT 'PreventOrdersUpdate',
GETDATE();
RAISERROR ('Updates on "Orders" table are not permitted.
Place a new order to add new products.', 16, 1);