新聞中心
CLR觸發(fā)器的原理比較簡單,但是實現(xiàn)起來要花一番功夫,筆者總結了以下經(jīng)驗,還有一個異常的實例。

創(chuàng)新互聯(lián)網(wǎng)絡公司擁有10余年的成都網(wǎng)站開發(fā)建設經(jīng)驗,上千客戶的共同信賴。提供網(wǎng)站制作、成都網(wǎng)站建設、網(wǎng)站開發(fā)、網(wǎng)站定制、外鏈、建網(wǎng)站、網(wǎng)站搭建、響應式網(wǎng)站、網(wǎng)頁設計師打造企業(yè)風格,提供周到的售前咨詢和貼心的售后服務
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ā)器內部調用 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.
此異常也是預期行為。
調用該CLR觸發(fā)器的例子
盡管引發(fā)了兩個異常,仍可以回滾事務,并且更改不會提交到表中。
- try
- {
- //用到此觸發(fā)器的方法
- }
- catch (SqlException ex)
- {
- if (ex.Number == 3991)
- {
- LabelInfor.Text = "同一張訂單必須是同一家供應商。";
- }
- }
- catch (Exception ex)
- {
- ......
- }
以上就是對CLR觸發(fā)器的實戰(zhàn)演練。
【編輯推薦】
- 淺析C#數(shù)組操作方法
- C#數(shù)組操作全面分析
- C#數(shù)組和串操作經(jīng)驗總結
- 為你解疑:CLR是什么?
- 分析與對比CLR Via C#靜態(tài)構造函數(shù)的性能
網(wǎng)站名稱:CLR觸發(fā)器實戰(zhàn)演練
文章分享:http://www.5511xx.com/article/cogejjg.html


咨詢
建站咨詢
