2016-12-07 63 views
0

我创建了一个存储过程,在发生错误时它应该回滚所有内容,我一直在寻找,但是我找不到弹出的错误。关于事务不匹配的SQL存储过程

[例外:在源“.net SqlClient数据提供”与过程‘ST_IV_ItemPrice.SP_Insert’错误数266.16.2发生在线路130事务计数EXECUTE后意外的SQL错误表示BEGIN的不匹配数和COMMIT语句。以前的计数= 1,当前计数= 0.]

我希望我可以在这里得到一些帮助。

CREATE PROCEDURE [dbo].[ST_IV_ItemPrice.SP_Insert] 
    /*parameters*/ 
AS 
BEGIN 
    IF OBJECT_ID(''tempdb..#tempPriceList'') IS NOT NULL 
     /*Then it exists*/ 
     DROP TABLE #tempPriceList 
    CREATE TABLE #tempPriceList(PriceListid int, NewCurrencyUnitPrice  decimal(19, 5)) 

    DECLARE @Error int, 
     @NextListid int, 
     @NewCurrencyUnitPrice decimal(19, 5), 
     @NoRounding int = 0, 
     @UserSpecified int = 4 



    BEGIN TRANSACTION 
    BEGIN TRY 
     /*Insert item to table*/ 

     SET @Id = SCOPE_IDENTITY() 
     SET @Error = @@ERROR 


     IF @Error = 0 AND @AutoGenerate = 1 
     BEGIN 
      INSERT INTO #tempPriceList(PriceListid, NewCurrencyUnitPrice) 
      VALUES(@Id, @Price) 

      WHILE(EXISTS(SELECT * FROM #tempPriceList)) 
      BEGIN 


      SELECT TOP 1 @NextListid = [id], @NewCurrencyUnitPrice =  [NewCurrencyUnitPrice] 
      FROM #tempPriceList 

      /*INSERT SELECT STATEMENT*/ 

      INSERT INTO #tempPriceList ([PriceListid],[NewCurrencyUnitPrice]) 
      Select [ListId] , [NewCurrencyUnitPrice] 


      IF @Error = 0 AND @SetExpiredDate = 1 AND @FromDate IS NOT NULL 
      BEGIN 
      /*Update item that is same as inserted and set to inactive*/ 


      END 

      DELETE FROM #tempPriceList WHERE PriceListid = @NextListid 

     END 
    END 
    END TRY 
    BEGIN CATCH 
     ROLLBACK TRANSACTION  
    END CATCH 

    IF @@TRANCOUNT>0 
     COMMIT TRANSACTION 

    RETURN @Error 
END 

回答

1
CREATE PROCEDURE [dbo].[ST_IV_ItemPrice.SP_Insert] 
    /*parameters*/ 
AS 
BEGIN 
    /* don't drop what does not belong to you */ 
    CREATE TABLE #tempPriceList(PriceListid int, NewCurrencyUnitPrice  decimal(19, 5)) 

    BEGIN TRY 
     /* begin/commit within a single code block */ 
     BEGIN TRANSACTION 

     /* some code */ 

     /* we are here if everything is ok */ 
     COMMIT TRANSACTION 
    END 
    END TRY 
    BEGIN CATCH 
     /* check xact_state instead of @@trancount, because @@trancount may be >0 whilst you are unable to commit/rollback anything */ 
     IF XACT_STATE() IN (-1, 1) 
      ROLLBACK TRANSACTION 

     /* do not suppress exceptions! */ 
     RAISERROR(...) 
    END CATCH 

    /* it will be dropped after you leave SP scope, but you may clean all created here by yourself; this is not required */ 
    IF OBJECT_ID('tempdb..#tempPriceList') IS NOT NULL 
     EXEC('DROP TABLE #tempPriceList') 

    RETURN @Error 
END 
+0

怎么写,但我仍然得到同样的错误 “事务计数EXECUTE后,我试图表明BEGIN和COMMIT语句的不匹配数。一个计数= 1,当前计数= 0] “ –

+0

我计划不要增加错误,因为我想在我的程序中处理它,并且不希望网站进入用户无法理解的错误页面 –

+0

当您陷入”CATCH“或当一切都好? –