且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

SQL-Server、TSQL、TRY-CATCH 块

更新时间:2023-02-06 11:27:02

您需要将测试条件封装在 EXEC 中才能将错误视为运行时问题.然后,您需要完全限定访问可能不存在的数据库的查询的对象,以便您可以避免使用 USE 语句.对于需要本地上下文的 OBJECTPROPERTY 等函数,您可以使用 sp_executesql 在不同的数据库上下文中运行查询并返回可用结果.

You need to encapsulate the test condition in an EXEC to get the error to be treated as a run-time issue. You then need to fully-qualify the objects for the queries that hit databases that might not exist so that you can avoid the USE statement. For functions such as OBJECTPROPERTY that require local context, you can use sp_executesql to run queries in a different database context and return a usable result.

DECLARE @TableName SYSNAME,
        @SQL NVARCHAR(MAX),
        @Result BIT

BEGIN TRY

    USE [master];
    SELECT TOP 1 * FROM sys.objects

    SET @TableName = N'sysjobhistory'
    SET @Result = 0
    SET @SQL = N'USE [msdb]; DECLARE @Result BIT;
                 SET @TempResult = OBJECTPROPERTY( OBJECT_ID(N''' + @TableName +
                 N'''), ''TableHasIdentity'')'

    EXEC sp_executesql @SQL,
                       N'@TempResult BIT OUTPUT',
                       @TempResult = @Result OUTPUT

    SELECT @Result AS [ResultThatCanBeUsedLocally]

    EXEC('USE [NotHere];')

    SELECT TOP 1 * FROM NotHere.sys.objects

END TRY
BEGIN CATCH

    PRINT 'Error!!'
    PRINT ERROR_MESSAGE()

END CATCH