简体   繁体   中英

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?

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.

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 )

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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