簡體   English   中英

SQL存儲過程中的事務不匹配

[英]SQL Stored Procedure on Transaction mismatch

我創建了一個存儲過程,當出現錯誤時它應該回滾所有內容,我一直在尋找,但是我找不到不斷彈出的錯誤。

[異常:源'.Net SqlClient數據提供者'在程序行'ST_IV_ItemPrice.SP_Insert'中的錯誤號266.16.2處發生意外的SQL錯誤。EXECUTE之后的事務計數指示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
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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM