Share via

how to throw error from my procedure so that sp_execute_remmote catches the faliure and returns npn 0 value

Ayush Shrivastava 120 Reputation points
2024-09-09T14:18:15.5266667+00:00

How to throw error from my procedure so that sp_execute_remote catches the failure and returns non 0 value.

Azure SQL Database
0 comments No comments

Answer accepted by question author

Amira Bedhiafi 41,641 Reputation points MVP Volunteer Moderator
2024-09-09T21:56:03.71+00:00

To throw an error from your stored procedure so that sp_execute_remote catches it and returns a non-zero value, you need to use the THROW or RAISEERROR statements within the stored procedure. These statements generate errors that propagate to the calling sp_execute_remote, which will handle the failure.

Example of using THROW:


CREATE PROCEDURE [dbo].[YourProcedureName]

AS

BEGIN

    BEGIN TRY

        -- Your procedure logic goes here

        -- Simulate an error if something goes wrong

        THROW 50000, 'An error occurred in the procedure.', 1;

    END TRY

    BEGIN CATCH

        -- Handle the error or log it, if needed, before re-throwing

        THROW;

    END CATCH

END

Example of using RAISEERROR:


CREATE PROCEDURE [dbo].[YourProcedureName]

AS

BEGIN

    BEGIN TRY

        -- Your procedure logic goes here

        -- Simulate an error

        RAISERROR('An error occurred in the procedure.', 16, 1);

    END TRY

    BEGIN CATCH

        -- Optionally handle the error or log it, then re-throw

        RAISERROR('Re-throwing error from CATCH block.', 16, 1);

    END CATCH

END

Using sp_execute_remote:

Once your procedure throws an error, when sp_execute_remote runs this procedure, it will catch the error and return a non-zero value. Here's an example of how to use sp_execute_remote to call this procedure remotely:


EXEC sp_execute_remote

    @data_source = N'YourExternalDataSource',

    @stmt = N'EXEC YourDatabase.dbo.YourProcedureName;';

If an error is thrown from the remote procedure, the error code returned by sp_execute_remote will be non-zero, indicating failure.

Was this answer helpful?


0 additional answers

Sort by: Most helpful

Your answer

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