存储过程中出现不匹配错误的问题

时间:2019-04-27 22:04:30

标签: sql-server

有人可以告诉我我的代码有什么问题吗?我已经尝试了很长时间,但是代码却无法正常工作。

Select语句未执行,并引发错误:

  

Msg 266,第16级,状态2,过程HW5INS2,第14行
  EXECUTE之后的事务计数表明不匹配的数目   BEGIN和COMMIT语句。上一个计数= 0,当前计数= 1。

该怎么办?

ALTER PROCEDURE HW5INS2
    -----LEVEL-2:ShipmentBoxes
    @boxID VARCHAR(16),
    @boxWeight NUMERIC(6,2),
    @boxHeight NUMERIC(5,2),
    @boxWidth NUMERIC(5,2),
    @boxLength NUMERIC(5,2),
    @packager SMALLINT,
    @shipDate SMALLDATETIME ='2018-03-02'  ----NOT REQUIRED
AS
BEGIN TRANSACTION
    ---------Test For Existence Of Parent Row: LOOK INTO Employees TABLE
    IF EXISTS (SELECT employeeID FROM Employees WHERE employeeID = @packager)
    BEGIN
        BEGIN TRANSACTION
        BEGIN TRY
            INSERT INTO ShipmentBoxes (boxID, boxWeight, boxHeight, boxWidth, boxLength, packager, shipDate)
            VALUES (@boxID, @boxWeight, @boxHeight, @boxWidth, @boxLength, @packager, @shipDate)

            SELECT * FROM ShipmentBoxes

            COMMIT
        END TRY
        BEGIN CATCH
            ROLLBACK TRANSACTION

            PRINT 'Error occurred while trying to insert the ShipmentBoxes table'
            SELECT
                ERROR_NUMBER() as errornumber,
                XACT_state() as xstate
        END CATCH
    END
    ELSE
    BEGIN
        -----PARENT DOESNOT EXIST, RETURN ERROR
        ROLLBACK TRANSACTION
        PRINT 'Error: PARENT does not exist'
    END

    RETURN

1 个答案:

答案 0 :(得分:-1)

该消息很清楚,您的BEGIN/END块中的一个或多个没有关闭语句END。另外,最好将所有内容保留在TRY/CATCH块中,以确保捕获所有错误并仅使用一个COMMIT/ROLLBACK语句(无冗余)。在以下版本中,您可以使用RAISERROR回滚事务并显示错误。

ALTER PROCEDURE HW5INS2
    @boxID varchar(16),
    @boxWeight numeric(6,2),
    @boxHeight numeric(5,2),
    @boxWidth numeric(5,2),
    @boxLength numeric(5,2),
    @packager smallint,
    @shipDate smalldatetime ='2018-03-02'  ----NOT REQUIRED
AS
BEGIN

    BEGIN TRY

        BEGIN TRANSACTION

            IF EXISTS(SELECT employeeID FROM Employees WHERE employeeID = @packager)
            BEGIN

                INSERT INTO ShipmentBoxes (boxID, boxWeight, boxHeight, boxWidth, boxLength, packager, shipDate)
                VALUES (@boxID, @boxWeight, @boxHeight, @boxWidth, @boxLength, @packager, @shipDate)

                SELECT * FROM ShipmentBoxes

                COMMIT  

            END
            ELSE
            BEGIN
              -- USE RAISERROR() TO CATCH THE ERROR AND ROLLBACK TRANSACTION. 
              RAISERROR('Error: PARENT DOESNOT EXIST',16,1)           

            END

    END TRY
    BEGIN CATCH

        ROLLBACK TRANSACTION

        PRINT 'Error Occured While Trying To Insert The ShipmentBoxes Table'
        SELECT
            ERROR_MESSAGE() as ErrorMessage, -- To Display the RAISERROR Message
            ERROR_NUMBER() as errornumber,
            XACT_state() as xstate

    END CATCH

END