Sql Server 2012中序列的真正需求是什么?
在 SQL Server 2012 (Denali) 中,我们有一个新功能序列。考虑下面的程序
/****** Create Sequence Object ******/
CREATE SEQUENCE GenerateSequence
START WITH 1
INCREMENT BY 1;
/****** Create a test Table ******/
Create TABLE tblTest
(
ID int NOT NULL PRIMARY KEY,
Name varchar(100) NOT NULL,
Age int NOT NULL
);
/****** Insert Some Records ******/
INSERT INTO tblTest(ID, Name, Age)
VALUES (NEXT VALUE FOR GenerateSequence, 'Name1',10),
(NEXT VALUE FOR GenerateSequence, 'Name2',20),
(NEXT VALUE FOR GenerateSequence, 'Name3',30),
(NEXT VALUE FOR GenerateSequence, 'Name4',40);
/****** Display result******/
SELECT * FROM tblTest;
输出
ID Name Age
1 Name1 10
2 Name2 20
3 Name3 30
4 Name4 40
我们可以使用像这样的标识列
Create TABLE tblTest
(
ID int NOT NULL PRIMARY KEY Identity,
Name varchar(100) NOT NULL,
Age int NOT NULL
);
,并且可以像这样填充
INSERT INTO tblTest(Name, Age)
VALUES ('Name1',10),
VALUES ('Name2',20)...
等来获得相同的输出
那么通过使用序列我们将获得什么额外的好处呢?
In SQL Server 2012 (Denali), we have a new feature Sequence. Consider the below program
/****** Create Sequence Object ******/
CREATE SEQUENCE GenerateSequence
START WITH 1
INCREMENT BY 1;
/****** Create a test Table ******/
Create TABLE tblTest
(
ID int NOT NULL PRIMARY KEY,
Name varchar(100) NOT NULL,
Age int NOT NULL
);
/****** Insert Some Records ******/
INSERT INTO tblTest(ID, Name, Age)
VALUES (NEXT VALUE FOR GenerateSequence, 'Name1',10),
(NEXT VALUE FOR GenerateSequence, 'Name2',20),
(NEXT VALUE FOR GenerateSequence, 'Name3',30),
(NEXT VALUE FOR GenerateSequence, 'Name4',40);
/****** Display result******/
SELECT * FROM tblTest;
Output
ID Name Age
1 Name1 10
2 Name2 20
3 Name3 30
4 Name4 40
Instead of this we can use an identity column like
Create TABLE tblTest
(
ID int NOT NULL PRIMARY KEY Identity,
Name varchar(100) NOT NULL,
Age int NOT NULL
);
and can populate like
INSERT INTO tblTest(Name, Age)
VALUES ('Name1',10),
VALUES ('Name2',20)...
etc. to get the same output
Then what extra benifit we will achieve by using sequence?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这可以在不同的数据库表之间使用,从而保持多个表之间的ID唯一。
查看 SQL SQL Server 2011 中的序列和创建数字序列
This can be used between different database tables, so that it keeps the ID unique between multiple tables.
Have a look at SQL Sequences and Create Sequence of Numbers in SQL Server 2011