Show command executed when SQL error occurs

Asked

Viewed 323 times

6

Considering the following command executed

BEGIN TRY  
    -- Generate a divide-by-zero error.  
    SELECT 1/0;  
END TRY  
BEGIN CATCH  
    SELECT  
        ERROR_NUMBER() AS ErrorNumber  
        ,ERROR_SEVERITY() AS ErrorSeverity  
        ,ERROR_STATE() AS ErrorState  
        ,ERROR_PROCEDURE() AS ErrorProcedure  
        ,ERROR_MESSAGE() AS ErrorMessage;  

END CATCH;  
GO 

The answer to it will be:

ErrorNumber
8134

ErrorSeverity
16

ErrorState
1

ErrorProcedure
NULL

ErrorMessage
Divide by zero error encountered.

Is there any way to get which execution block was executed to generate this exception?

I wish the answer was:

Command

'SELECT 1/0;'

2 answers

4

Jhonathan, it’s usually not a conventional error exit, but this bit can help you:

BEGIN TRY  
    -- Generate a divide-by-zero error.  

    SELECT 1 / 0;
END TRY
BEGIN CATCH
    SELECT [qt].text
      FROM [sys].[dm_exec_connections] AS [A]
           CROSS APPLY [sys].[dm_exec_sql_text]([A].[most_recent_sql_handle]) AS [qt]
     WHERE [session_id] = @@SPID;
END CATCH;  
GO

But in my opinion, you could collect these errors otherwise, in an audit.

Sqlserver: Query error audit

0

A solution and you create a variable to store the description of the block being executed and concatenate in the message.

declare @BlocoExe varchar(max)

BEGIN TRY  
    -- Generate a divide-by-zero error. 
    set @BlocoExe  = 'Bloco exe: SELECT 1/0 - Erro:'; -- descrição do bloco
    SELECT 1/0;  
END TRY  
BEGIN CATCH  
    SELECT  
        ERROR_NUMBER() AS ErrorNumber  
        ,ERROR_SEVERITY() AS ErrorSeverity  
        ,ERROR_STATE() AS ErrorState  
        ,ERROR_PROCEDURE() AS ErrorProcedure  
        , @BlocoExe + ERROR_MESSAGE()  AS ErrorMessage ;  

END CATCH;  
GO 
  • You can not do this, because the application that I will apply this model are several commands with various records.

  • yes, but how many errors will return? specify your question better.

  • I want him to return any errors he gives.

  • And what’s the problem? Just use the variable and concatenate

Browser other questions tagged

You are not signed in. Login or sign up in order to post.