How to get output value from a stored procedure in case of error

Aleksei Galeev 40 Reputation points
2023-07-03T15:14:50.5033333+00:00

There is a test SP which has one output parameter only:

IF OBJECT_ID('dbo.USP_SAMPLE_PROCEDURE', 'P') IS NOT NULL
   DROP PROCEDURE dbo.USP_SAMPLE_PROCEDURE;
GO

CREATE PROCEDURE USP_SAMPLE_PROCEDURE
( 
	@Param1 int OUTPUT 
)
AS
BEGIN
	SET XACT_ABORT, NOCOUNT ON;
	
	BEGIN TRY
		SELECT @Param1 = 123;
		;THROW 50001, 'Test error', 0;
	END TRY
    BEGIN CATCH
		SELECT @Param1 = 5;
		-- Echo error information to the caller.
		;THROW;
    END CATCH
END

As you can see, I set some value for the @Param1 in case of normal flow and in case of error.

What is interesting about my code is that I cannot get the value 5. Here is my call:

DECLARE @Param1 int;
BEGIN TRY
	EXEC dbo.USP_SAMPLE_PROCEDURE @Param1=@Param1 OUTPUT;
	SELECT @Param1 AS [FROM TRY]
END TRY
BEGIN CATCH
	SELECT @Param1 AS [FROM CATCH]
END CATCH

The result is NULL instead of 5. What am I doing wrong?

SQL Server Other
{count} votes

Accepted answer
  1. Erland Sommarskog 121.4K Reputation points MVP Volunteer Moderator
    2023-07-03T21:16:28.0033333+00:00

    You are not doing anything wrong. The semantics for output parameters in T-SQL is copy-in/copy-out. But because an exception is raised, the copy-out never happens.

    I have a little more discussion about this here: https://www.sommarskog.se/error_handling/Part2.html#TRY-CATCH

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2023-07-03T15:48:39.7033333+00:00

    The sp is returning an error rather than a result set. Output parameters are returned in the result set after the row data. Normally the exec would copy the output parameter result to the output parameter, but the error result bypasses this step.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.