How does SQL Server generate values in an identity column?

自作多情 提交于 2019-12-12 05:38:07

问题


My question is if I have two batch inserts into one table in parallel, how does SQL Server create identity values?

I mean, if in one session I insert multiple rows (Row1-Row2-Row3) and simultaneously another session inserts multiple rows (Row4-Row5-Row6) at the same time, the result would be like this?

Row1
Row2
Row3
Row4
Row5
Row6

or maybe something like this?

Row1
Row6
Row3
Row5
Row4
Row2

回答1:


You are making the common fallacy of assuming an order in the table. Tables have no order. Only results have order, which is undetermined unless an explicit ORDER BY is specified.

You may ask a different question: how is the identity generated value assigned in case of concurrent inserts? The answer is simple: it doesn't matter. And if you make any assumption about the order then your code is broken. Same goes for gaps. Your application should work even if the identities generated are completely random, and correctly written application will work if the identity is completely random. Use SCOPE_IDENTITY() to retrieve the last inserted identity. Better still, use the OUTPUT clause of INSERT, it works for multi-row inserts too.

For the record: the identities are generated in the order on which operations acquire access to the log stream.



来源:https://stackoverflow.com/questions/12577411/how-does-sql-server-generate-values-in-an-identity-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!