Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

E.g.

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, i.e. in this case so they match a=1, b=1 and a=2, b=2.

like image 930
Simon D Avatar asked Mar 12 '26 02:03

Simon D


1 Answers

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
like image 111
greyalien007 Avatar answered Mar 14 '26 16:03

greyalien007



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!