[英]Order guarantee for identity assignment in multi-row insert in SQL Server
使用表值構造器(http://msdn.microsoft.com/zh-cn/library/dd776382(v=sql.100).aspx)插入多行時,是否保證填充的任何標識列的順序都匹配TVC中的行?
例如
CREATE TABLE A (a int identity(1, 1), b int)
INSERT INTO A(b) VALUES (1), (2)
引擎保證的值是否以與b相同的順序分配,即在這種情況下,它們匹配a = 1,b = 1和a = 2,b = 2。
above帶我在上面的評論,並且知道insert / select + order by的行為將保證生成身份順序(#4: 來自此博客 )
假設您希望基於類別ID生成身份,則可以按以下方式使用表值構造函數來實現目標(不確定是否滿足其他約束)。
insert into thetable(CategoryId, CategoryName)
select *
from
(values
(101, 'Bikes'),
(103, 'Clothes'),
(102, 'Accessories')
) AS Category(CategoryID, CategoryName)
order by CategoryId
只要您將記錄插入一張照片中就可以了。 例如,在插入后,如果刪除a = 2的記錄,然后再次重新插入值b = 2,則標識列的值將為max(a)+1
展示
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.