Using SQL Server 2012 T-SQL New Features
By 13 Oct 2011
,
Introduction
SQL Server 2012 “Denali” is the next major release of Microsoft database server. There are some new features that are added to T-SQL to make common tasks much easier. I will show how to use some of the new features in this article.Sequence
Generating a sequence number, a.k.a. auto number, is a common task in an enterprise application. For a single table, you can specify identity field. But, if you want to have database wide sequential number, then you must devise something by yourself before SQL Server 2012. One solution to this problem is to create a table that has a numeric field can be used to store sequential number, then use SQL to increase it every time used one. In SQL Server 2012, we have a new solution - use Sequence.Create Sequence
To create a Sequence in SQL Server 2012 is very simple. You can create it with SQL Server Management Studio or T-SQL.- Create Sequence with SQL Server Management Studio
In Object Explorer window of SQL Server Management Studio, there is a Sequences node under Database -> [Database Name] -> Programmability. You can right click on it to bring up context menu, and then choose New Sequence… to open the New Sequence window. In New Sequence window, you can define the new Sequence, like Sequence Name, Sequence schema, Data type, Precision, Start value, Increment by, etc. After entering all the required information, click OK to save it. The new Sequence will show up in Sequences node. - Create Sequence with T-SQL
The following T-SQL script is used to create a new Sequence:Collapse | Copy CodeCREATE SEQUENCE DemoSequence START WITH 1 INCREMENT BY 1;
Use Sequence
The newNEXT VALUE FOR
T-SQL keyword is used to get the next sequential number from a Sequence.
Collapse | Copy Code
SELECT VALUE FOR DemoSequence
One thing I want to mention in here is Sequence doesn’t support transaction, if you run this script:
Collapse | Copy Code
BEGIN TRAN
SELECT NEXT VALUE FOR dbo.DemoSequence
ROLLBACK TRAN
You can see even the transaction is rolled back at the end. The NEXT VALUE FOR
will still return the next sequential number. This behavior is consistent with identity field.
No comments:
Post a Comment