0

When executing my stored procedure, why do I get the following error message?

Msg 266, Level 16, State 2, Procedure spAddCustomer, Line 0 [Batch Start Line 21]
Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 1, current count = 2.

Anything help, thanks.

Stored procedure code:

CREATE PROC spAddCustomer
    @FirstName VARCHAR = INPUT,
    @LastName VARCHAR = INPUT,
    @EmailAddress VARCHAR = INPUT,
    @PhoneNumber VARCHAR = INPUT
AS
BEGIN TRY
BEGIN TRANSACTION 
    INSERT INTO sales.CustomerPII (FirstName, LastName, EmailAddress, PhoneNumber)
    VALUES (@FirstName, @LastName, @EmailAddress, @PhoneNumber);

    COMMIT TRANSACTION
END TRY
BEGIN CATCH
--Rows inserted still exist
--SELECT ERROR_NUMBER()
    --ROLLBACK TRANSACTION --Any transaction work will be undone
END CATCH;

Executed

EXEC spAddCustomer 'FirstTest', 'LastTest', 'EmailTest', 'AddressTest';
2
  • Bad habits to kick : declaring VARCHAR without (length) - you should always provide a length for any varchar variables and parameters that you use. For parameter, if you omit the explicit length, you get a parameter of exactly ONE character in length - which is typically not what you want ..... Commented Nov 16, 2018 at 21:56
  • add BEGIN after AS and add END at the end of the store procedure. Commented Nov 16, 2018 at 23:27

2 Answers 2

3

Un-comment this line:

ROLLBACK TRANSACTION --Any transaction work will be undone
Sign up to request clarification or add additional context in comments.

1 Comment

I agree with @ikram. It appears that execution is going into the CATCH block, but no action is being taken there. You may also consider re-throwing the exception here, or logging. As written, it will roll back silently.
1

Try setting XACT_ABORT ON in the stored procedure. When SET XACT_ABORT is ON and T-SQL statement raises a run-time error, SQL Server automatically rolls back the current transaction. Try it as follows:

USE AdventureWorks2016CTP3
GO
CREATE PROC spAddCustomer
@FirstName varchar = INPUT,
@LastName varchar = INPUT,
@EmailAddress varchar = INPUT,
@PhoneNumber varchar = INPUT
AS

SET NOCOUNT ON 
SET XACT_ABORT ON
BEGIN TRY
BEGIN TRANSACTION 
INSERT INTO sales.CustomerPII (FirstName,LastName,EmailAddress,PhoneNumber)
VALUES(@FirstName, @LastName, @EmailAddress, @PhoneNumber);
COMMIT TRANSACTION
END TRY
BEGIN CATCH

END CATCH;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.