SQL Server 如何在标识列中生成值?

How does SQL Server generate values in an identity column?(SQL Server 如何在标识列中生成值?)
本文介绍了SQL Server 如何在标识列中生成值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我的问题是,如果我有两个并行的批量插入到一个表中,SQL Server 如何创建标识值?

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

我的意思是,如果在一个会话中我插入多行(Row1-Row2-Row3),同时另一个会话同时插入多行(Row4-Row5-Row6),结果会是这样吗?

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

或者类似的东西?

Row1
Row6
Row3
Row5
Row4
Row2

推荐答案

您犯了假定表格中的顺序的常见谬误.表没有顺序.只有结果才有顺序,除非指定了明确的 ORDER BY,否则顺序是不确定的.

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.

您可能会问一个不同的问题:在并发插入的情况下,如何分配标识生成的值?答案很简单:没关系.如果您对订单做出任何假设,那么您的代码就会被破坏.间隙也是如此.即使生成的身份完全随机,您的应用程序也应该可以运行,如果身份完全随机,正确编写的应用程序运行.使用 SCOPE_IDENTITY() 检索最后一个插入的身份.更好的是,使用 OUTPUT 子句INSERT,它也适用于多行插入.

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.

这篇关于SQL Server 如何在标识列中生成值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Query with t(n) and multiple cross joins(使用 t(n) 和多个交叉连接进行查询)
Unpacking a binary string with TSQL(使用 TSQL 解包二进制字符串)
Max rows in SQL table where PK is INT 32 when seed starts at max negative value?(当种子以最大负值开始时,SQL 表中的最大行数其中 PK 为 INT 32?)
Inner Join and Group By in SQL with out an aggregate function.(SQL 中的内部连接和分组依据,没有聚合函数.)
Add a default constraint to an existing field with values(向具有值的现有字段添加默认约束)
SQL remove from running total(SQL 从运行总数中删除)