TSQL错误:COMMIT TRANSACTION请求没有相应的BEGIN TRANSACTION

时间:2014-11-29 21:39:15

标签: sql-server tsql

我正在学习TSQL并在尝试更新product表中的列时遇到错误。它告诉我COMMIT TRANSACTION请求没有相应的BEGIN TRANSACTION,但是我的sproc顶部有一个begin transaction。任何帮助表示赞赏。

 alter proc dbo.ProductOrders

@ProdId int, @ProductPrice smallmoney
as
Declare @timesOrdered int, @ProductId int,
Declare  @counter int,  @return_value int
Declare @time timestamp, @irowCount int

set transaction isolation level read uncommitted
set nocount on
set @counter = 0
while(@counter < 3)
begin

begin transaction

select @ProductId = ProductId, @ProductPrice = UnitPrice, @time = ProductStamp
from dbo.Products
where ProductId = @ProdId

select @timesOrdered = COUNT(ProductId)
from dbo.Products
where ProductId = @ProdId 




if(@timesOrdered < 2)
begin
raiserror('Product hasnt been ordered enough to raise price',16,1)
rollback transaction 
break
end





EXEC    @return_value = [dbo].[UpdateProduct]
        @ProductPrice = @ProductPrice,
        @ProdId = @ProdId,
        @time = @time,
        @eRowCount = @irowCount OUTPUT



SELECT  'Return Value' = @return_value





if @return_value <> 0
begin
raiserror ('Product not updated, error occured',16,1,@return_value) 
return @return_value
end

if(@irowCount = 0)
begin
print 'another transaction is trying to access the data'
set @counter += 1
rollback transaction
end

raiserror('Price updated',16,1)
commit transaction
set @counter = 0
return 0

    end--end while loop
    if(@counter = 3)
    begin
    raiserror('try again later',16,1)
    return 99
    end

2 个答案:

答案 0 :(得分:1)

你的代码正在调用ROLLBACK然后也是COMMIT,试试这个修正:

...
    if(@irowCount = 0)
    begin
      print 'another transaction is trying to access the data'
      set @counter += 1
      rollback transaction  
    end
    else
    begin
      raiserror('Price updated',16,1)
      commit transaction  
      set @counter = 0
    end
...

您在RETURN之后错过了ROLLBACK吗?

您的代码正在点击ROLLBACK,然后又在几行之后调用COMMIT ...

一旦您致电ROLLBACK,就不再有COMMIT的任何交易,因此您可以开始新的交易(不是您想要的我确定),或者确保您只需致电{ {1}}在未调用COMMIT的情况下。

答案 1 :(得分:0)

我最近在分布式环境中遇到了与SQLserver 2012类似的问题。基本上我们使用多个线程发送批量请求。即使其中一个线程失败,所有与该线程相关的记录都在数据库中可用。在调查配置后,我们发现我们没有在连接字符串中禁用“Enlist”。默认情况下,Enlist值为true且已启用。禁用Enlist值后,我们没有观察到上述异常,多线程场景正常运行。添加以下配置为web.config连接字符串。

Enlist=false