且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-05-27 01:08:55

您犯了假定表格中的顺序的常见谬误.表没有顺序.只有结果才有顺序,除非指定了明确的 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.