Sequence Number

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Sequence Number相关的知识,希望对你有一定的参考价值。

Sequence 在当前transaction scope之外产生,当事务回滚时,Sequence number 不会回滚。 

1,Create Sequence syntax

CREATE SEQUENCE [schema_name . ] sequence_name
    [ AS [ built_in_integer_type | user-defined_integer_type ] ]
    [ START WITH <constant> ]
    [ INCREMENT BY <constant> ]
    [ { MINVALUE [ <constant> ] } | { NO MINVALUE } ]
    [ { MAXVALUE [ <constant> ] } | { NO MAXVALUE } ]
    [ CYCLE | { NO CYCLE } ]
    [ { CACHE [ <constant> ] } | { NO CACHE } ]
    [ ; ]

[ CACHE [<constant> ] | NO CACHE ]              

Increases performance for applications that use sequence objects by minimizing the number of disk ios that are required to generate sequence numbers. Defaults to CACHE.

For example, if a cache size of 50 is chosen, SQL Server does not keep 50 individual values cached. It only caches the current value and the number of values left in the cache. This means that the amount of memory required to store the cache is always two instances of the data type of the sequence object.

When created with the CACHE option, an unexpected shutdown (such as a power failure) may result in the loss of sequence numbers remaining in the cache.

 

2,使用 NEXT VALUE FOR function 获取Sequence value

NEXT VALUE FOR [ schema_name . ]  sequence_name
   [ OVER (<over_order_by_clause>) ]

Remarks

When the NEXT VALUE FOR function is used in a query or default constraint, if the same sequence object is used more than once, or if the same sequence object is used both in the statement supplying the values, and in a default constraint being executed, the same value will be returned for all columns referencing the same sequence within a row in the result set.
The NEXT VALUE FOR function is nondeterministic, and is only allowed in contexts where the number of generated sequence values is well defined. Below is the definition of how many values will be used for each referenced sequence object in a given statement:

  • SELECT  - For each referenced sequence object, a new value is generated once per row in the result of the statement.

  • INSERT … VALUES - For each referenced sequence object, a new value is generated once for each inserted row in the statement.

  • UPDATE  - For each referenced sequence object, a new value is generated for each row being updated by the statement.

  • Procedural statements (such as DECLARE, SET, etc.) - For each referenced sequence object, a new value is generated for each statement.

3, Examples

CREATE SCHEMA Test;
GO

CREATE SEQUENCE Test.CountBy1
    START WITH 1
    INCREMENT BY 1 ;
GO

A. Using a sequence in a select statement

SELECT NEXT VALUE FOR Test.CountBy1 AS FirstUse, NEXT VALUE FOR Test.CountBy1 AS SecondUse;

技术分享

B. Setting a variable to the next sequence value

DECLARE @myvar1 bigint = NEXT VALUE FOR Test.CountBy1
DECLARE @myvar2 bigint ;
DECLARE @myvar3 bigint ;
SET @myvar2 = NEXT VALUE FOR Test.CountBy1 ;
SELECT @myvar3 = NEXT VALUE FOR Test.CountBy1 ;
SELECT @myvar1 AS myvar1, @myvar2 AS myvar2, @myvar3 AS myvar3 ;

C. Using a sequence with a ranking window function

SELECT NEXT VALUE FOR Test.CountBy1 OVER (ORDER BY LastName) AS ListNumber,
    FirstName, LastName
FROM Person.Contact ;
GO

D. Using the NEXT VALUE FOR function in an INSERT statement

INSERT Test.TestTable (CounterColumn,Name)
VALUES (NEXT VALUE FOR Test.CountBy1, Syed) ;


5, Remark

Sequence numbers are generated outside the scope of the current transaction. They are consumed whether the transaction using the sequence number is committed or rolled back.

Cache management

To improve performance, SQL Server pre-allocates the number of sequence numbers specified by the CACHE argument.

For an example, a new sequence is created with a starting value of 1 and a cache size of 15. When the first value is needed, values 1 through 15 are made available from memory. The last cached value (15) is written to the system tables on the disk. When all 15 numbers are used, the next request (for number 16) will cause the cache to be allocated again. The new last cached value (30) will be written to the system tables.

If the Database Engine is stopped after you use 22 numbers, the next intended sequence number in memory (23) is written to the system tables, replacing the previously stored number.

After SQL Server restarts and a sequence number is needed, the starting number is read from the system tables (23). The cache amount of 15 numbers (23-38) is allocated to memory and the next non-cache number (39) is written to the system tables.

If the Database Engine stops abnormally for an event such as a power failure, the sequence restarts with the number read from system tables (39). Any sequence numbers allocated to memory (but never requested by a user or application) are lost. This functionality may leave gaps, but guarantees that the same value will never be issued two times for a single sequence object unless it is defined as CYCLE or is manually restarted.

The cache is maintained in memory by tracking the current value (the last value issued) and the number of values left in the cache. Therefore, the amount of memory used by the cache is always two instances of the data type of the sequence object.

Setting the cache argument to NO CACHE writes the current sequence value to the system tables every time that a sequence is used. This might slow performance by increasing disk access, but reduces the chance of unintended gaps. Gaps can still occur if numbers are requested using the NEXT VALUE FOR or sp_sequence_get_range functions, but then the numbers are either not used or are used in uncommitted transactions.

When a sequence object uses the CACHE option, if you restart the sequence object, or alter the INCREMENT, CYCLE, MINVALUE, MAXVALUE, or the cache size properties, it will cause the cache to be written to the system tables before the change occurs. Then the cache is reloaded starting with the current value (i.e. no numbers are skipped). Changing the cache size takes effect immediately.

CACHE option when cached values are available              

The following process occurs every time that a sequence object is requested to generate the next value for the CACHE option if there are unused values available in the in-memory cache for the sequence object.

  1. The next value for the sequence object is calculated.

  2. The new current value for the sequence object is updated in memory.

  3. The calculated value is returned to the calling statement.

CACHE option when the cache is exhausted              

The following process occurs every time a sequence object is requested to generate the next value for the CACHE option if the cache has been exhausted:

  1. The next value for the sequence object is calculated.

  2. The last value for the new cache is calculated.

  3. The system table row for the sequence object is locked, and the value calculated in step 2 (the last value) is written to the system table. A cache-exhausted xevent is fired to notify the user of the new persisted value.

NO CACHE option              

The following process occurs every time that a sequence object is requested to generate the next value for the NO CACHE option:

  1. The next value for the sequence object is calculated.

  2. The new current value for the sequence object is written to the system table.

  3. The calculated value is returned to the calling statement.

参考doc:

CREATE SEQUENCE (Transact-SQL)

ALTER SEQUENCE (Transact-SQL)

NEXT VALUE FOR (Transact-SQL)

Sequence Numbers

以上是关于Sequence Number的主要内容,如果未能解决你的问题,请参考以下文章

如何sql 在表中创建一个sequence

为啥我们有 pack_sequence() 时还需要 pack_padded_sequence()?

ORACLE Sequence 自增长

第六章 UVM中的sequence

Oracle中Sequence使用

你知道Oracle的Sequence序列吗?