事務回滾后,自增ID仍然增加


回滾后,自增ID仍然增加。

比如當前ID是7,插入一條數據后,又回滾了。
然后你再插入一條數據,此時插入成功,這時候你的ID不是8,而是9.
因為雖然你之前插入回滾,但是ID還是自增了。


如果你認為自增ID不應該被事務化,那么其他事務不得不等待着,檢查自增ID是被使用還是被回滾,這就導致阻塞。比如下面的例子,A表使用自增ID。
User 1
------------
begin transaction
insert into A ...
insert into B ...
update C ...
insert into D ...
commit


User 2
-----------
begin transaction
insert into A ...
insert into B ...
commit


看以上的例子代碼,如果自增ID也要被事務化,那么假設user 2 的事務在user 1執行后的1毫秒后執行,那么他的插入到A表不得不等待User 1的整個事務結束,檢查第一個自增ID是不是被使用了。這就導致阻塞。

自增ID不被事務化是設計使然,不是bug,如果需要緊密連續的自增序列,建議采用其他方法生成。

--不連續沒關係,需要時候生成一列
if object_id('tb')is not null drop table tb
go
create table tb(ID int )
insert tb select 1
insert tb select 2
insert tb select 5
insert tb select 18
insert tb select 13
select id ,[newid]=(select count(*) from tb where id<=t.id) from tb t order by [newid]
/*id          newid      
----------- -----------
1           1
2           2
5           3
13          4
18          5

(影響 5 個資料列)
*/
 

本文出自 “一只博客” 博客,請務必保留此出處http://cnn237111.blog.51cto.com/2359144/607957


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM