How to capture error message returned from linked server?

断了今生、忘了曾经 提交于 2019-12-24 09:44:39

问题


How can I capture an error message returned from a linked server?

As an example, if I run the following command in SQL Server Management Studio:

BEGIN TRY
 exec ('select * from xxx') at my_linked_server
END TRY

BEGIN CATCH
  print  'ErrorNumber...'+  CAST(ERROR_NUMBER() as varchar)
  print  'ErrorSeverity...'+  CAST(ERROR_SEVERITY() as varchar)
  print  'ErrorState...'+  CAST(ERROR_STATE() as varchar)
  print  'ErrorProcedure...'+ IsNull(ERROR_PROCEDURE(),'')
  print  'ErrorLine...'+  CAST(ERROR_LINE() as varchar)
  print  'ErrorMessage...'+  IsNull(ERROR_MESSAGE(),'')
END CATCH

I get the following results:

OLE DB provider "MSDASQL" for linked server "my_linked_server" returned message "[Informix][Informix ODBC Driver][Informix]The specified table (xxx) is not in the database.". ErrorNumber...7215 ErrorSeverity...17 ErrorState...1 ErrorProcedure... ErrorLine...3 ErrorMessage...Could not execute statement on remote server 'my_linked_server'.

Does SQL Server store the OLE DB provider error? (It would be useful to capture this info for debugging.)


回答1:


I had this same problem. I found out how to get around it by passing the try catch to the linked server and getting the error back using the OUTPUT parameter. For example:

    SET @command = '
    BEGIN TRY
        exec (''select * from xxx'') 
        SELECT @resultOUT = @@ERROR
    END TRY
    BEGIN CATCH
        SELECT @resultOUT = @@ERROR
    END CATCH'
    SET @ParmDefinition = N'@resultOUT nvarchar(5) OUTPUT'
    exec my_linked_server.sp_executesql 
        @command, 
        @ParmDefinition, 
        @resultOUT=@result OUTPUT


来源:https://stackoverflow.com/questions/2168207/how-to-capture-error-message-returned-from-linked-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!