In this blog, I will give you a walk through about a new feature introduced in sql server 2012 – Sequence.
What
is a Sequence?
It is basically a user
defined object that generates numeric values in sequential order. User can
define the order in which the sequence has to be generated. It can be in
ascending or descending order. One major
difference with identity column is that sequence is not associated with a
particular table. The application has to maintain the relationship between
sequence and table.
Syntax is as given below -:
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 } ] [ ; ]
By default, the sequence
accepts bigint as datatype. The
datatype can be a built in (eg-: tinyint , smallint , etc) or user
defined one.
The START value must be assigned with a value less than or equal to the
maximum and greater than or equal to the minimum value of the sequence
object.
The INCREMENT value is by default 1. It cannot be set to 0. If the
values specified is negative, then sequence returns numbers in descending order
else vice-versa.
The MINVALUE value specifies the lower limit of sequence. By default it
is the minimum value of the data type.
The MAXVALUE value specifies the upper limit of sequence. By default it
is the maximum value of the data type.
The CYCLE|NOCYCLE option specifies whether the sequence has to be
restart from MINVALUE/MAXVALUE. By default the value is NOCYCLE.
The sequence created will be listed under Sequence folder as shown below. From the Management studio >> Databasenode >> Programmability >> Sequences.
How to create a sequence using script?
In the below script a
sequence named IncrementBy1 is created that increases by one every time that it is used. This is an example for incrementing sequence.
Sreejith GopinathanPosted Apr 11, 2013, 11:39 AM
Hi Joxin, really interesting one, thanks for sharing
Jean PaulPosted Apr 9, 2013, 8:04 AM
Good feature Joxin.. Thank You for sharing!