为什么在 SQL Server 2012 中,对于变量表回滚操作无法有效?

3

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

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

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

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 因此,在这里事务回滚不起作用。为什么在这里不起作用?我做错了什么吗?
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

我修改了我的问题。感谢您分享知识。但是问题仍然存在。为什么对于变量表不起作用?

我发布的链接比我能提供的更详细地介绍了这一点。


我修改了我的问题。感谢您的知识分享。但问题仍然存在。为什么它对于变量表不起作用? - unknown
已更新我的回答。希望能有所帮助。 - Kritner
3
修改表变量的操作会被记录到tempdb事务日志中,但它们运行在内部系统事务下,每个语句执行后都会提交该事务,但该事务不参与外部用户事务。 - Martin Smith
2
还有一个更详细的关于其他差异的。http://dba.stackexchange.com/questions/16385/whats-the-difference-between-a-temp-table-and-table-variable-in-sql-server/16386#16386 - Martin Smith
1
@MartinSmith - 在 SQL Server 中有你不知道的东西吗 :D - Pரதீப்
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接