Introduction

SQL Server 2012 comes with many features, one of which is SEQUENCE. SEQUENCE works similarly to the IDENTITY value but the IDENTITY column has limited scope, for examle it is applied to a specific column and a specific table and it does the control by the application code. The SEQUENCE object is not limited to a column or table but it is scoped to an entire database and it is controlled by application code.

Syntax

CREATE SEQUENCE [schema name . ] sequence name
[ AS [ built in integer type | user-defined integer type ] ]
[ START WITH integer constant]
[ INCREMENT BY integer constant ]
[ { MINVALUE [integer constant] } | { NO MINVALUE } ]
[ { MAXVALUE [integer constant] } | { NO MAXVALUE } ]
[ CYCLE | { NO CYCLE } ]
[ { CACHE [integer constant] } | { NO CACHE } ]
[ ; ]

Parameters/Arguments description

Sequence objects are generated outside of the current transaction. If we set the cache argument to NOCACHE then SQL Server writes the value of the sequence to the system table every time the NEXT VALUE FOR function is called for the sequence object.

The following are the advantages of the Sequence object:

Example

In this example, I have created one Sequence object and created two tables that use the Sequence.

CREATE SEQUENCE [dbo].[TableNextId]
AS
[int]
START WITH 1000
INCREMENT BY 1
MINVALUE 1000
MAXVALUE 10000
CYCLE
CACHE

CREATE TABLE TableA
(
Id INT NOT NULL,
Code VARCHAR(20),
Name VARCHAR(20)
)

CREATE TABLE TableB
(
Id INT NOT NULL,
Code VARCHAR(20),
Name VARCHAR(20)
)

INSERT INTO TableA VALUES (NEXT VALUE FOR DBO.TableNextId,'Test code table A', 'Test name table A')
INSERT INTO TableB VALUES (NEXT VALUE FOR DBO.TableNextId,'Test code table B', 'Test name table B')
INSERT
INTO TableA VALUES (NEXT VALUE FOR DBO.TableNextId,'Test code table A', 'Test name table A')
INSERT INTO TableB VALUES (NEXT VALUE FOR DBO.TableNextId,'Test code table B', 'Test name table B'

Sequence object

Alter and Drop the Sequence object

We can also alter and drop the existing sequence. We can alter the increment, cycle, minimum value and maximum value of a sequence. Start with cannot be used with the alter statement.

ALTER SEQUENCE TableNextId
INCREMENT BY 2
MINVALUE 1000
MAXVALUE 100000
DROP SEQUENCE TableNextId

DROP SEQUENCE TableNextId

Where can we find existing Sequence object in Database? We have the following two ways:

  1. The system table “Sys.Sequences” contains all the sequences that are created on the database.

    Sys.Sequences

  2. From the Management Studio.

     Management Studio

"Database" >> "Programmability" >> "Sequences".

Conclusion

Using a Sequence Object we can generate a sequence number and this Sequence can be share with multiple tables. It is similar to IDENTITY but has a greater scope.