简体   繁体   English

SQL Server多行插入中身份分配的顺序保证

[英]Order guarantee for identity assignment in multi-row insert in SQL Server

When using a Table Value Constructor (http://msdn.microsoft.com/en-us/library/dd776382(v=sql.100).aspx) to insert multiple rows, is the order of any identity column populated guaranteed to match the rows in the TVC? 使用表值构造器(http://msdn.microsoft.com/zh-cn/library/dd776382(v=sql.100).aspx)插入多行时,是否保证填充的任何标识列的顺序都匹配TVC中的行?

Eg 例如

CREATE TABLE A (a int identity(1, 1), b int)

INSERT INTO A(b) VALUES (1), (2)

Are the values of a guaranteed by the engine to be assigned in the same order as b, ie in this case so they match a=1, b=1 and a=2, b=2. 引擎保证的值是否以与b相同的顺序分配,即在这种情况下,它们匹配a = 1,b = 1和a = 2,b = 2。

Piggybacking on my comment above, and knowing that the behavior of an insert / select+order by will guarantee generation of identity order (#4: from this blog ) above带我在上面的评论,并且知道insert / select + order by的行为将保证生成身份顺序(#4: 来自此博客

You can use the table value constructor in the following fashion to accomplish your goal (not sure if this satisfies your other constraints) assuming you wanted your identity generation to be based on category id. 假设您希望基于类别ID生成身份,则可以按以下方式使用表值构造函数来实现目标(不确定是否满足其他约束)。

insert into thetable(CategoryId, CategoryName)
select *
from
  (values
    (101, 'Bikes'),
    (103, 'Clothes'),
    (102, 'Accessories')
  ) AS Category(CategoryID, CategoryName)
order by CategoryId

It depends as long as your inserting the records in one shot . 只要您将记录插入一张照片中就可以了。 For example after inserting if you delete the record where a=2 and then again re insert the value b=2 ,then identity column's value will be the max(a)+1 例如,在插入后,如果删除a = 2的记录,然后再次重新插入值b = 2,则标识列的值将为max(a)+1

To demonstrate 展示

 DECLARE @Sample TABLE
 (a int identity(1, 1), b int)

 Insert into @Sample values (1),(2)

a   b
1   1
2   2

 Delete from @Sample where a=2

 Insert into @Sample values (2)
 Select * from @Sample

 a  b
 1  1
 3  2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM