且构网

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

如何在 SQL Server 表中插入 auto_increment 键

更新时间:2022-02-03 22:19:44

从你整篇评论来看,你在表上有一个不是标识列的主键.

Judging by you comments throughout, you have a primary key on the table that is not an identity column.

如果您的 SQL Server 版本是 SQL 2012,您应该查看序列:http://msdn.microsoft.com/en-us/library/ff878091.aspx

If your version of SQL Server is SQL 2012 you should look into sequences: http://msdn.microsoft.com/en-us/library/ff878091.aspx

在其他版本中,您需要使用主键列的 IDENTITY 属性 (http://msdn.microsoft.com/en-us/library/aa933196(v=sql.80).aspx) 重新创建表或使用两步法.

In other versions you either need to recreate the table using the IDENTITY property (http://msdn.microsoft.com/en-us/library/aa933196(v=sql.80).aspx) for the primary key column or use a two step approach.

如果您采用两步法,您需要确保并发运行的插入操作最终不会使用相同的新值.最简单的方法是将选择和插入组合成一个值并使用可序列化表提示:

If you go with the two step approach you need to make sure that concurrently running inserts won't end up using the same new value. The easiest way to do that is this is by combining the select and the insert into one value and using the serializable table hint:

CREATE TABLE dbo.Tbl1(id INT PRIMARY KEY, val1 INT, val2 INT)

INSERT INTO dbo.Tbl1(id, val1, val2)
VALUES((SELECT ISNULL(MAX(id)+1,0) FROM dbo.Tbl1 WITH(SERIALIZABLE, UPDLOCK)), 42, 47);

SELECT * FROM dbo.Tbl1;