查询无效的外部时无法捕获错误 Table

Cannot Catch error when querying an invalid External Table

当您根据另一个 Azure SQL 数据库中不存在的 table 创建外部 table 时。

SELECT * 
FROM invalid_external_table

抛出以下错误信息:

Msg 46823, Level 16, State 1, Procedure
Error retrieving data from {azure database}. The underlying error message received was: 'Invalid object name 'dbo.invalid_table'.'.

我正在处理的问题是您似乎无法捕获此错误。

以下代码导致相同的错误:

BEGIN TRY
    SELECT * 
    FROM invalid_external_table 
END TRY
BEGIN CATCH
    PRINT 'caught exception'
END CATCH

我正在 Azure SQL 数据库中查询外部 table,该数据库基于来自另一个 SQL 数据库的 table。

是否可以在查询外部 table 之前捕获此错误或验证外部 table?

根据the documentation

TRY…CATCH constructs do not trap the following conditions:

  • Errors that occur during statement-level recompilation, such as object name resolution errors that occur after compilation because of deferred name resolution.

If an error occurs during compilation or statement-level recompilation at a lower execution level (for example, when executing sp_executesql or a user-defined stored procedure) inside the TRY block, the error occurs at a lower level than the TRY…CATCH construct and will be handled by the associated CATCH block.

这也不是外部表特有的,下面会报错:

BEGIN TRY
    SELECT * FROM msdb.dbo.InvalidTable;
END TRY
BEGIN CATCH
    PRINT 'caught exception';
END CATCH

但是如果你动态执行SQL,那么你会到达catch块,例如:

BEGIN TRY
    EXECUTE sp_executeSQL N'SELECT * FROM msdb.dbo.InvalidTable;';
END TRY
BEGIN CATCH
    PRINT 'caught exception';
END CATCH