SQL-Server, TSQL, TRY-CATCH block(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 块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:SQL-Server、TSQL、TRY-CATCH 块


- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- 更改自动增量起始编号? 2021-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- SQL 临时表问题 2022-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01