CLR觸發(fā)器實戰(zhàn)演練
CLR觸發(fā)器的原理比較簡單,但是實現(xiàn)起來要花一番功夫,筆者總結(jié)了以下經(jīng)驗,還有一個異常的實例。
CLR觸發(fā)器實現(xiàn)代碼:
- [Microsoft.SqlServer.Server.SqlTrigger(Name = "Trigger1", Target =
- "ERP_STOCKYaoHuoDingDan", Event = "FOR INSERT")]
- public static void DingDanIDSameGongYingShangGUIDMustSame()
- {
- using (SqlConnection connection = new SqlConnection
- (@"context connection=true"))
- {
- connection.Open();
- SqlCommand command = new SqlCommand(@"SELECT COUNT(A.DingDanID)
- FROM ERP_STOCKYaoHuoDingDan AS
- A,INSERTED AS B WHERE A.DingDanID=B.DingDanID AND
- A.GongYingShangGUID<>B.GongYingShangGUID", connection);
- int i=(int)command.ExecuteScalar();
- if (i>0)
- {
- try
- {
- //如果要插入的記錄不合法,則回滾.
- Transaction trans = Transaction.Current;
- trans.Rollback();
- }
- catch (SqlException ex)
- {
- connection.Close();
- }
- }
- }
- }
當在CLR觸發(fā)器內(nèi)部調(diào)用 Transaction.Rollback 方法時,將引發(fā)異常并顯示不明確的錯誤消息,必須在try/catch 塊中包裝此方法或命令。您會看到如下錯誤消息:
Msg 6549, Level 16, State 1, Procedure trig_InsertValidator, Line 0 A .NET Framework error occurred during execution of user defined routine or aggregate 'trig_InsertValidator': System.Data.SqlClient.SqlException: Transaction is not allowed to roll back inside a user defined routine, trigger or aggregate because the transaction is not started in that CLR level. Change application logic to enforce strict transaction nesting… User transaction, if any, will be rolled back.
此異常是預期行為,需要 try/catch 塊才能繼續(xù)執(zhí)行代碼。當完成執(zhí)行CLR觸發(fā)器代碼時,將引發(fā)另一個異常。
Msg 3991, Level 16, State 1, Procedure trig_InsertValidator, Line 1 The context transaction which was active before entering user defined routine, trigger or aggregate "trig_InsertValidator" has been ended inside of it, which is not allowed. Change application logic to enforce strict transaction nesting. The statement has been terminated.
此異常也是預期行為。
調(diào)用該CLR觸發(fā)器的例子
盡管引發(fā)了兩個異常,仍可以回滾事務,并且更改不會提交到表中。
- try
- {
- //用到此觸發(fā)器的方法
- }
- catch (SqlException ex)
- {
- if (ex.Number == 3991)
- {
- LabelInfor.Text = "同一張訂單必須是同一家供應商。";
- }
- }
- catch (Exception ex)
- {
- ......
- }
以上就是對CLR觸發(fā)器的實戰(zhàn)演練。
【編輯推薦】