在表中插入多行时,是否能保证它们按照我指定的顺序插入?例如,采用以下内容:
DECLARE @blah TABLE
(
ID INT IDENTITY(1, 1),
Name VARCHAR(100) NOT NULL
);
INSERT INTO @blah (Name)
VALUES('Timmy'),
('Jonny'),
('Sally');
SELECT * FROM @blah
能否保证 Sally
的主键高于 Timmy
?
最佳答案
非常相似的question之前有人问过。
您可以在INSERT
中指定ORDER BY
。
如果您这样做,IDENTITY
值的生成顺序将保证与 INSERT
中指定的 ORDER BY
相匹配。
使用您的示例:
DECLARE @blah TABLE
(
ID INT IDENTITY(1, 1) NOT NULL,
Name VARCHAR(100) NOT NULL
);
INSERT INTO @blah (Name)
SELECT T.Name
FROM
(
VALUES
('Timmy'),
('Jonny'),
('Sally')
) AS T(Name)
ORDER BY T.Name;
SELECT
T.ID
,T.Name
FROM @blah AS T
ORDER BY T.ID;
结果是:
+----+-------+
| ID | Name |
+----+-------+
| 1 | Jonny |
| 2 | Sally |
| 3 | Timmy |
+----+-------+
也就是说,Name
已经排序,并按照这个顺序生成了ID。保证 Jonny 将具有最低的 ID,Timmy 将具有最高的 ID,Sally 将在他们之间具有 ID。生成的ID值之间可能存在间隙,但保证它们的相对顺序。
如果您未在 INSERT
中指定 ORDER BY
,则可以按不同的顺序生成结果 IDENTITY
ID。
请注意,即使在 INSERT
中使用 ORDER BY
,也无法保证表中行的实际物理顺序,唯一的保证是生成的 ID。
在一个问题中INSERT INTO as SELECT with ORDER BY MS 的 Umachandar Jayachandran 说道:
The only guarantee is that the identity values will be generated based on the ORDER BY clause. But there is no guarantee for the order of insertion of the rows into the table.
他给出了一个链接到Ordering guarantees in SQL Server ,来自 SQL Server 引擎团队的 Conor Cunningham 说道:
- INSERT queries that use SELECT with ORDER BY to populate rows guarantees how identity values are computed but not the order in which the rows are inserted
该帖子的评论中有一个 MS 知识库文章的链接:The behavior of the IDENTITY function when used with SELECT INTO or INSERT .. SELECT queries that contain an ORDER BY clause ,它更详细地解释了它。它说:
If you want the
IDENTITY
values to be assigned in a sequential fashion that follows the ordering in theORDER BY
clause, create a table that contains a column with theIDENTITY
property and then run anINSERT ... SELECT ... ORDER BY
query to populate this table.
我会将这篇知识库文章视为官方文档,并认为这种行为是有保证的。
关于sql - 插入带有标识的多行时是否保证顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34621188/