Introduction
Many DBAs that use Oracle asks for sequences in SQL Server. Now, SQL Server 2012 includes a nice and easy way to create sequences like Oracle. If you have an earlier SQL Server version, you can read a great article to create custom sequences by James Skipwith: Create custom sequences in SQL Server
In this article we will work with SQL Server 2012 or later.
Demostration
First of all, let’s create a simple table with 5 values:
CREATE TABLE test (names varchar(15)) GO INSERT INTO test values ('John'), ('James'), ('Jasdon'), ('Mary'), ('Jessica')
Now, we are going to create a sequence from 1 to 10 named tenNumbers. This sequence will create values incremented by 1.
CREATE SEQUENCE tenNumbers AS tinyint START WITH 1 INCREMENT BY 1 MINVALUE 1 MAXVALUE 10 CYCLE ; GO
All good so far, we can now use the sequence and the table created:
SELECT NEXT VALUE FOR tenNumbers AS ID, names FROM test; GO
The first time than you run the query the values displayed will be the following:
If you run the same query again, you will notice that the sequence continues from 6 to 10.
To reset the sequence to 1 you can use the following query:
ALTER SEQUENCE tenNumbers RESTART WITH 1 ;
In this new example, I am going to create a table with the value int and insert data using sequences:
CREATE TABLE test2 (column1 INT) GO INSERT test2 (column1) values (NEXT Value for tenNumbers), (NEXT Value for tenNumbers), (NEXT Value for tenNumbers), (NEXT Value for tenNumbers), (NEXT Value for tenNumbers)
To verify the values we can use this select query:
select * from test2
Finally, if it is necessary to drop the sequence, you can use the DROP SEQUENCE
drop sequence tenNumbers
Conclusion.
In this article, we reviewed the sequences and different examples to create, alter, reset them in SQL Server tables.
References.
Sequence numbers in SQL Server:
http://msdn.microsoft.com/en-us/library/ff878058(v=sql.110).aspx
Sequences in Oracle: