我在 T-SQL 中的 Try Catch 有什么问题? [英] What is wrong with my Try Catch in T-SQL?

查看:31
本文介绍了我在 T-SQL 中的 Try Catch 有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 SQL Server 2008,当我在 Management Studio 中运行此语句时,Catch 块中的 Select 语句按预期执行

I am using SQL Server 2008 and when I run this Statement in Management studio the Select statement in the Catch Block is executed as expected

BEGIN TRY
 INSERT INTO IDontExist(ProductID)
 VALUES(1)
END TRY
BEGIN CATCH
SELECT 'There was an error! ' + ERROR_MESSAGE()
END CATCH

但是,当我运行此语句时,Catch 块中的语句永远不会执行,而错误仅显示在结果选项卡中

However when I run this statement the statement in the Catch Block is never executed and instead the error is just displayed in the results tab

BEGIN TRY
  Select * from IDontExist
END TRY
BEGIN CATCH
  SELECT 'There was an error! ' + ERROR_MESSAGE()
END CATCH

它们都返回相同的错误号 '208' 'Invalid Object Name: IDontExist' 那么为什么一个会被处理而另一个没有?

They both return the same error number '208' 'Invalid Object Name: IDontExist' so why would one get handled and the other not?

推荐答案

我根本没有遇到 CATCH 块.

I don't get the CATCH block hit at all.

那是因为代码不会编译,因为对象不存在,没有生成计划,所以没有运行到 CATCH 块.

That's because the code won't compile, because the object doesn't exist, no plan is generated, so nothing runs to hit the CATCH block.

你可以永远点击这个catch块,所以你的测试/示例有问题.您可以在不同的范围(例如嵌套的存储过程)中命中外部 catch 块

You can never hit this catch block so somethign is wrong with your testing/example. You can hit an outer catch block in a different scope (eg nested stored procs)

我使用的是 SQL Server 2005 SP3

I'm using SQL Server 2005 SP3

这取决于延迟名称解析何时适用,与语句级重新编译有关.

It depends when deferred name resolution applies, related to statement level recompilation.

  • 在我的例子中,整个批次两次都失败,并且没有发生语句级重新编译,因此没有延迟名称解析

  • In my case, the whole batch fails both times and no statement level recompilation happens so no deferred name resolution

在 OP 的情况下,批处理编译并运行,但随后在运行代码中出现语句级重新编译/延迟名称解析错误

In OP's case, the batch compiles and runs but then has a statement level recompilation/deferred name resolution error in running code

我要去寻找一些关于为什么它不同的参考资料,因为 BOL 并没有说太多,厄兰·索马斯科格

I'm off to find some references about why it's different, given BOL doesn't say much, neither does Erland Sommarskog

这篇关于我在 T-SQL 中的 Try Catch 有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆