gpt4 book ai didi

sql - T-SQL try ... catch 和多个批处理(2 begin...end,if...else)

转载 作者:行者123 更新时间:2023-12-03 02:33:34 25 4
gpt4 key购买 nike

我正在尝试了解 T-SQL 中 try ... catch 构造的工作原理。

所以我在 MSDN 上读过文章:http://msdn.microsoft.com/en-us/library/ms175976.aspx

我对这个说法有点困惑:TRY…CATCH 构造不能跨越多个批处理。 TRY…CATCH 构造不能跨越多个 Transact-SQL 语句 block 。例如,TRY…CATCH 构造不能跨越 Transact-SQL 语句的两个 BEGIN…END block ,也不能跨越 IF…ELSE 构造。

这意味着 try ... catch 不能跨越 2 个 BEGIN...END block ,也不能跨越 IF...ELSE 结构。

但是,我已经尝试过并且有效! (2005年和2008年)

有人能解释一下为什么吗?看起来 MSDN 上有一些错误。

看看我的测试脚本:

print 'start'
begin transaction test_tran
begin try
-- first begin ... end
begin
-- some statements
print 'begin ... end - #1'
end
-- second begin ... end
begin
print 'begin ... end - #2'
-- statement with error
select 1/0 -- division by zero
end
print 'end of try'
end try
begin catch
print 'catch'
goto RollbackTran
end catch

-- commit
print 'commit'
commit transaction test_tran

-- rollback
RollbackTran:
BEGIN
print 'rollback'
WHILE @@TRANCOUNT > 0
begin
ROLLBACK TRANSACTION test_tran
print 'actual rollback'
end
END

结果:

start
begin ... end - #1
begin ... end - #2

(0 row(s) affected)
catch
rollback
actual rollback

它有效(2 个开始...结束 block )!但 MSDN 说不应该。IF ... ELSE 语句也是如此。

谁能解释一下吗?

最佳答案

T-SQL 批处理通常由 GO 语句表示。他们说你不能这样做:

BEGIN TRY

PRINT 'statement 1'

GO -- Cannot have a GO to end batch inside of a TRY / CATCH

PRINT 'statement 2'

END TRY
BEGIN CATCH

PRINT 'Catch Block'

END CATCH

同样你不能:

IF (1 = 1)
BEGIN
BEGIN TRY

PRINT 'test'

END -- Cannot END a block that began prior to the TRY / CATCH

END TRY
BEGIN CATCH

PRINT 'Catch block'

END CATCH

你也不能这样做:

IF (1 = 1)
BEGIN TRY

PRINT 'statement 1'

ELSE -- Cannot do ELSE for an IF that started prior to the TRY / CATCH
PRINT 'statement 2'

END TRY
BEGIN CATCH

PRINT 'Catch Block'

END CATCH

关于sql - T-SQL try ... catch 和多个批处理(2 begin...end,if...else),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9599975/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com