为什么 SQL Server 2012 中的变量表回滚不起作用?

问题描述 投票:0回答:1

我创建了一个变量表。在我的存储过程中,有很多事务。

现在,每当发生错误时,我想回滚特定事务,该事务包含一些从变量表中插入、更新或删除记录的语句。

这只是我实际问题的一个例子:

declare @tab table (val int)

insert into @tab select 2
insert into @tab select 3
insert into @tab select 4

select * from @tab

begin tran
begin try
    update @tab set val = 1
    select 1/0;
    commit
end try
begin catch
    rollback
end catch

select * from @tab

实际产量:-
enter image description here

我的预期输出是:-

enter image description here

所以这里事务回滚不起作用。为什么它在这里不起作用?我是不是做错了什么?

sql sql-server sql-server-2012 transactions rollback
1个回答
6
投票

您使用的不是

temp
表格,而是
variable
表格。 是有区别的。

临时表可以处理事务,而变量表则不能。请参阅http://blog.sqlauthority.com/2009/12/28/sql-server-difference-temp-table-and-table-variable-effect-of-transaction/

如果您要将变量表

@tab
更改为临时表
#tab
,您将获得所需的行为。

临时表和变量表之间的差异:https://dba.stackexchange.com/questions/16385/whats-the-difference- Between-a-temp-table-and-table-variable-in-sql-server/16386 #16386

我修改了我的问题。感谢您的知识分享。但问题仍然是一样的。为什么它不适用于变量表?

我上面发布的链接比我能提供的更详细。

© www.soinside.com 2019 - 2024. All rights reserved.