SQL-Server、TSQL、TRY-CATCH 块

SQL-Server, TSQL, TRY-CATCH block(SQL-Server、TSQL、TRY-CATCH 块)
本文介绍了SQL-Server、TSQL、TRY-CATCH 块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我在处理 try/catch 错误时遇到了问题.让我们看看我的(简单)代码:

I'm having a problem with try/catch error-handling. Let's have a look on my (simple) code:

BEGIN TRY
print 'important'
use myDB1; -- no problem, the myDB1 is in place...
select * from dbo.Tab1;
use myDB2;
--here error, the myDB2 is not there, 
--but error handling doesn't jump into catch-block

select * from dbo.Tab2;
END TRY
BEGIN CATCH
    print 'myDB2 is not there'
END CATCH

我知道,我可以说:

select * from myDB2.dbo.Tab2 无需更改为 myDB2,但是当我需要检查(例如..)一个表是否具有标识时

select * from myDB2.dbo.Tab2 without changing to myDB2, but when I need to check (for example..) if a table has an identity

(((SELECT OBJECTPROPERTY( OBJECT_ID('myDB2.dbo.'+ @TableName), 'TableHasIdentity'))= 1)

我必须从 myDB2 运行它,否则我会得到错误的结果.那么我怎样才能在 catch-block 中捕获错误呢?

I must run this from myDB2, otherwise I'll get a wrong result. So how can I catch the error in the catch-block?

感谢您的帮助

珀克洛特

推荐答案

您需要将测试条件封装在 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

这篇关于SQL-Server、TSQL、TRY-CATCH 块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Query with t(n) and multiple cross joins(使用 t(n) 和多个交叉连接进行查询)
Unpacking a binary string with TSQL(使用 TSQL 解包二进制字符串)
Max rows in SQL table where PK is INT 32 when seed starts at max negative value?(当种子以最大负值开始时,SQL 表中的最大行数其中 PK 为 INT 32?)
Inner Join and Group By in SQL with out an aggregate function.(SQL 中的内部连接和分组依据,没有聚合函数.)
Add a default constraint to an existing field with values(向具有值的现有字段添加默认约束)
SQL remove from running total(SQL 从运行总数中删除)