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

后端 未结 2 1271
萌比男神i
萌比男神i 2020-12-21 17:09

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 populate

相关标签:
2条回答
  • 2020-12-21 17:13

    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
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题