本文介绍了如何检查内部交易或外部是否发生错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,

我创建了一个存储过程并使用了Transaction Inside Try Catch块。我在事务之前放了一些代码行。如果发生错误,它将被catch块捕获。现在如果我把rollback tran放在catch中并且在tran之前发生错误,那么这是一个错误。如何在tran内部发生错误?



例如这里是一个示例程序

Hello ,
I have created a stored Procedure and have used Transaction Inside Try Catch block. I have put some lines of code before transaction to. if an error occurs it will be caught by the catch block. Now if i put rollback tran inside catch and error occurs before tran , then it is a mistake. how will i know if the error occurred inside tran ?

For example here is a sample procedure

Create Procedure Test
@Input varchar(10)
As
Begin
 Begin Try
    Declare @Value int;
    Set @Value = @Input

     Begin Tran
      Insert into abc value (@Value);
     
     Commit Tran
 End Try

 Begin Catch
      Rollback Tran
 End Catch     

End

<pre>

Here an error will occur because @Value is of type int and i am assigning it a string value.
SO Execution will pass on to the catch block. There i have put rollback tran, but the transaction nerver started so how can it rollback ??

推荐答案

Begin Try
    Begin Tran
     INSERT INTO Invoices (InvoiceNumber, CustomerID, InvoiceDate) VALUES (@IN, @CID, @IDT);
     INSERT INTO InvoiceLines (InvoiceNumber, ProductID) VALUES (@IN, 1234)
     INSERT INTO InvoiceLines (InvoiceNumber, ProductID) VALUES (@IN, 1235)
    Commit Tran
End Try

Begin Catch
     Rollback Tran
End Catch

当任何事情失败时,ROLLBACK撤消它们。

And when anything fails, the ROLLBACK undoes them all.


这篇关于如何检查内部交易或外部是否发生错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 21:52