August 16, 2012

SQL Server 2012 - Binding Sequence to a Column‏




Continuing my series on SQL Server 2012, today we will learn about Sequence which is an object in SQL Server 2012 and can be used to generate customized sequence numbers. Although it is independent of objects, however an object can bind it. In this post, we will see how to use that as default value for a column

Create a sequence named my_seq

create sequence my_seq
    as int
    start with 1
    increment by 1

GO

Create a table in which one of the columns has a default value of my_seq

create table testing (col1 int, col2 int default next value for my_seq)

Now add some data to the table

insert into testing (col1)
select 34 union all
select 6

Select data from the table and see what col2 returns

select * from testing 

result

Col2 returns unique numbers. It should be noted that if the sequence is used by many objects, the value may not be sequential i.e. some values may be used somewhere else.

This way we can use sequence object to generate unique numbers like an identity column


Did you like this post?
kick it on DotNetKicks.com
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Madhivanan,an MSc computer Science graduate from Chennai-India, works as a works as a Lead Subject Matter Expert at a company that simplifies BIG data. He started his career as a developer working with Visual Basic 6.0, SQL Server 2000 and Crystal Report 8. As years went by, he started working more on writing queries in SQL Server. He now has good level of knowledge in SQLServer, Oracle, MySQL and PostgreSQL as well. He is also one of the leading posters at www.sqlteam.com and a moderator at www.sql-server-performance.com. His T-sql blog is at http://beyondrelational.com/blogs/madhivanan

 
  Feedback:

comments

0 Responses to "SQL Server 2012 - Binding Sequence to a Column‏"
 

Copyright © 2009-2014 All Rights Reserved for SQLServerCurry.com by Suprotim Agarwal | Terms and Conditions