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 块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

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

相关文档推荐

ibtmp1是非压缩的innodb临时表的独立表空间,通过innodb_temp_data_file_path参数指定文件的路径,文件名和大小,默认配置为ibtmp1:12M:autoextend,也就是说在文件系统磁盘足够的情况下,这个文件大小是可以无限增长的。 为了避免ibtmp1文件无止境的暴涨导致
SQL query to group by day(按天分组的 SQL 查询)
What does SQL clause quot;GROUP BY 1quot; mean?(SQL 子句“GROUP BY 1是什么意思?意思是?)
MySQL groupwise MAX() returns unexpected results(MySQL groupwise MAX() 返回意外结果)
MySQL SELECT most frequent by group(MySQL SELECT 按组最频繁)
Include missing months in Group By query(在 Group By 查询中包含缺失的月份)