4

I have a SEQUENCE that I used to set the transaction folio of a table:

CREATE SEQUENCE [Seq].[Folio] 
 AS [bigint]
 START WITH 114090
 INCREMENT BY 1
 MINVALUE -9223372036854775808
 MAXVALUE 9223372036854775807
 CACHE

Today just for curiousity I did a:

SELECT folio 
FROM transactions
ORDER BY folio DESC

and what was the surprise that there are gaps, so there are missing folios in the table.

Example:

  • 898, 897, 894, 892, 890, 889 ...

That means that something is happening. Just to give more information, the INSERT stored procedure that I used has the following before the INSERT INTO...

DECLARE @numfolio int

SELECT @numfolio = NEXT VALUE FOR  Seq.Folio

When saving the information from my application I used database transactions, so if everything goes well then the app does the COMMIT TRANSACTION and if not I do the ROLLBACK TRANSACTION.

I think that the origin of the problem is the transaction, so when there is an error the NEXT VALUE of the sequence has been already generated and the ROLLBACK has no effects on that.

Any clue how to solve this in order to have a perfect sequence without gaps?

4

1 回答 1

6

所以,关于序列,你应该了解一些事情。

  1. 它不是事务性的,所以是的,一旦事务检索到值,回滚不会恢复它。
  2. 序列的值是分批分配的,所以假设你将缓存大小设置为 10,抓取一个值,然后重新启动服务器,会有 10 的间隙。

至于如何获得完美的序列,可能唯一的方法是从可序列化事务中的表中获取最大值。现在您应该问自己的问题是“它们真的需要顺序吗?”。

于 2013-05-09T22:55:11.527 回答