分析概括CLR觸發(fā)器的例子
CLR有很多值得學(xué)習(xí)的地方,這里我們主要介紹創(chuàng)建CLR對象,包括介紹CLR觸發(fā)器等方面,希望你可以從中學(xué)到東西。
一 創(chuàng)建CLR對象
1.在解決方案中添加新的C#SQL數(shù)據(jù)庫項(xiàng)目,命名為“ServiceClient”
2.為你的目標(biāo)數(shù)據(jù)庫選擇或添加注釋。(如果未被提示:右擊ServiceClient項(xiàng)目,選擇屬性,數(shù)據(jù)庫,瀏覽并選擇你的連接)
3.為創(chuàng)建的服務(wù)添加聲明
1)在解決方案瀏覽器中右擊“service”項(xiàng)目,選擇“調(diào)試”>“Start New Instance”
2)服務(wù)運(yùn)行:右擊“ServiceClient”項(xiàng)目,選擇“Add Service Reference”
3)在“Service URI”中輸入:http://localhost:8000/services
4)點(diǎn)擊“OK”
二 CLR觸發(fā)器案例
- [Microsoft.SqlServer.Server.SqlTrigger(Name="Trigger1",Target="ERP_STOCKYaoHuoDingDan",Event="FORINSERT")]
 - publicstaticvoidDingDanIDSameGongYingShangGUIDMustSame()
 - {
 - using(SqlConnectionconnection=newSqlConnection(@"contextconnection=true"))
 - {
 - connection.Open();
 - SqlCommandcommand=newSqlCommand(@"SELECTCOUNT(A.DingDanID)FROMERP_STOCKYaoHuoDingDanASA,INSERTEDASBWHEREA.DingDanID=B.DingDanIDANDA.GongYingShangGUID<>B.GongYingShangGUID",connection);
 - inti=(int)command.ExecuteScalar();
 - if(i>0)
 - {
 - try
 - {
 - //如果要插入的記錄不合法,則回滾.
 - TransactionTransactiontrans=Transaction.Current;
 - trans.Rollback();
 - }
 - catch(SqlExceptionex)
 - {
 
當(dāng)在觸發(fā)器內(nèi)部調(diào)用Transaction.Rollback方法時(shí),將引發(fā)異常并顯示不明確的錯誤消息,必須在try/catch塊中包裝此方法或命令。您會看到如下錯誤消息:
- Msg6549,Level16,State1,Proceduretrig_InsertValidator,Line0A.NETFrameworkerroroccurredduringexecutionofuserdefinedroutineoraggregate
 - 'trig_InsertValidator':System.Data.SqlClient.SqlException:Transactionisnotallowedtorollbackinsideauserdefinedroutine,
 - triggeroraggregatebecausethetransactionisnotstartedinthatCLRlevel.Changeapplicationlogictoenforcestricttransactionnesting…Usertransaction,ifany,willberolledback.
 - 此異常是預(yù)期行為,需要try/catch塊才能繼續(xù)執(zhí)行代碼。當(dāng)完成執(zhí)行觸發(fā)器代碼時(shí),將引發(fā)另一個異常。
 - Msg3991,Level16,State1,Proceduretrig_InsertValidator,Line1Thecontexttransactionwhichwasactivebeforeenteringuserdefinedroutine,
 - triggeroraggregate"trig_InsertValidator"hasbeenendedinsideofit,whichisnotallowed.Changeapplicationlogictoenforcestricttransactionnesting.
 - Thestatementhasbeenterminated.此異常也是預(yù)期行為。
 - }
 - }
 - connection.Close();
 - }
 - }
 
調(diào)用CLR觸發(fā)器的例子
盡管引發(fā)了兩個異常,仍可以回滾事務(wù),并且更改不會提交到表中。
- try
 - {
 - //用到此觸發(fā)器的方法
 - }
 - catch(SqlExceptionex)
 - {
 - if(ex.Number==3991)
 - {
 - LabelInfor.Text="同一張訂單必須是同一家供應(yīng)商。";
 - }
 - }
 - catch(Exceptionex)
 - {
 - }
 
【編輯推薦】















 
 
 
 
 
 
 