2014-01-23 319 views
1

我有存儲過程,我在其中有一個事務。錯誤:ROLLBACK TRANSACTION請求沒有相應的BEGIN TRANSACTION

當我與SQL Server Management Studio中執行它沒有錯誤,但是當我用我的C#代碼執行它出現以下錯誤:

The ROLLBACK TRANSACTION request has no corresponding BEGIN TRANSACTION

的代碼是:

CREATE PROCEDURE [dbo].[AddHardDisk] 
    @name nvarchar(50), @brand nvarchar(50), @serial nvarchar(50), @cost float, @seller nvarchar(50),@note nvarchar(1000),@buyDate Date, 
    @size int ,@moneyType nvarchar(50) 

AS 

    DECLARE @addedDeviceID int 

BEGIN TRY 
    BEGIN TRAN 

     insert into Product(Name,Brand,Serial,Cost,Seller,Note,MoneyType,BuyDate) 
     values(@name,@brand,@serial,@cost,@seller,@note,@moneyType,@buyDate) 

     select @addedDeviceID =SCOPE_IDENTITY() 

     insert into HardDisk(ID,size) 
     values(@addedDeviceID,@size) 

     exec DecreaseMoneyFromFund @moneyType,@cost   

    COMMIT   
END TRY 
BEGIN CATCH 

    IF @@TRANCOUNT > 0 
     ROLLBACK 
END CATCH 
+0

你可以發佈你的C#代碼調用這個存儲過程的相關部分嗎? DecreaseMoneyFromFund過程也在做什麼? – abhi

+0

你能否發佈'DecreaseMoneyFromFund'的源代碼? –

+0

問題出現在SQL中,而不是C# – wruckie

回答

1

TRAN的範圍是你的TRY塊,所以在回滾的地方它不存在。切換它:BEGIN TRAN 然後 BEGIN TRY。

回滾必須在事務範圍內發生,而不是在它之前或之後。修改後的代碼:

CREATE PROCEDURE [dbo].[AddHardDisk] 
    @name nvarchar(50), @brand nvarchar(50), @serial nvarchar(50), @cost float, @seller nvarchar(50),@note nvarchar(1000),@buyDate Date, 
    @size int ,@moneyType nvarchar(50) 

AS 

    DECLARE @addedDeviceID int 

BEGIN TRAN 
    BEGIN TRY 

     insert into Product(Name,Brand,Serial,Cost,Seller,Note,MoneyType,BuyDate) 
     values(@name,@brand,@serial,@cost,@seller,@note,@moneyType,@buyDate) 

     select @addedDeviceID =SCOPE_IDENTITY() 

     insert into HardDisk(ID,size) 
     values(@addedDeviceID,@size) 

     exec DecreaseMoneyFromFund @moneyType,@cost   

     COMMIT   
    END TRY 
    BEGIN CATCH 
     IF @@TRANCOUNT > 0 
      ROLLBACK 
    END CATCH 
END TRAN 
+0

,你剛剛抽籤得更快。但我希望將tran嵌套在我的try/catch中 – wruckie

0

這是我用於Sp的Emply shell。我想你可能會錯過'Commit Tran'

BEGIN TRY ; 
    BEGIN TRAN; 
     BEGIN   

--Insert SQL Here 
     END 
IF @@TRANCOUNT > 0 
COMMIT TRAN ;  
END TRY 

BEGIN CATCH ; 
    DECLARE @ERROR_MESSAGE VARCHAR(200) ; 
    DECLARE @ERROR_SEVERITY INT ; 
    DECLARE @ERROR_STATE INT ; 

    SET @ERROR_MESSAGE = ERROR_MESSAGE() ; 
    SET @ERROR_SEVERITY = ERROR_SEVERITY() ; 
    SET @ERROR_STATE = ERROR_STATE() ; 

    RAISERROR (@ERROR_MESSAGE, -- Message text. 
        @ERROR_SEVERITY , -- Severity. 
        @ERROR_STATE -- State. 
       ); 

Select @ERROR_MESSAGE 

IF @@TRANCOUNT > 0 
     ROLLBACK TRAN ; 

END CATCH ; 
相關問題