SQL Server - Print Child SP Error Message

Rahul Polaboina 181 Reputation points
2022-02-22T23:41:32.867+00:00

I am executing a system store Proc inside a user defined stored proc, I would like help to store the error message returned by the system sp and print it from the parent sp. Below is the code of the system stored proc which is being executed from parent stored proc

EXEC msdb.dbo.sp_send_dbmail
@Anton _name = @profilename,
@recipients = @recipientslist ,
@Tomas Podoba = @tableHTML,--@tableHTML,--@bodycontent,
@Tomas Podoba _format = 'HTML',
@Gaydamak _attachments = @fileattachment,
@subject = @subjectname;

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
12,946 questions
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,566 questions
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. Naomi 7,361 Reputation points
    2022-02-22T23:54:20.857+00:00

    Did you try to put this call into BEGIN TRY / BEGIN CATCH statements?


  2. LiHong-MSFT 10,046 Reputation points
    2022-02-23T03:19:31.133+00:00

    Hi @Rahul Polaboina
    You can use try ... catch and in catch block you can use ERROR_MESSAGE(), ERROR_LINE(), ERROR_PROCEDURE(), ERROR_STATE(), etc functions.
    Try this:

    DECLARE  
      @ErrorMessage   varchar(2000)  
     ,@ErrorSeverity  tinyint  
     ,@ErrorState     tinyint  
      
    BEGIN TRY  
    /*  Your code here  */  
    END TRY  
      
    BEGIN CATCH  
        SET @ErrorMessage  = ERROR_MESSAGE()  
        SET @ErrorSeverity = ERROR_SEVERITY()  
        SET @ErrorState    = ERROR_STATE()  
        RAISERROR(@ErrorMessage, @ErrorSeverity, @ErrorState)  
        BREAK  
    END CATCH  
    

    Please refer to this thread for more details.

    Best regards,
    LiHong


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

  3. Deleted

    This answer has been deleted due to a violation of our Code of Conduct. The answer was manually reported or identified through automated detection before action was taken. Please refer to our Code of Conduct for more information.


    Comments have been turned off. Learn more