17

I am using SQL Server Management Studio and I want to change an auto increment primary key value of a table row, with a different value. SQL Server Management Studio after opening the table for edit, shows this field grayed for all rows, of course.

Is it possible? I want to use the number of a row we deleted by mistake, therefore it's valid (there is no conflict with other primary key values) and - most important of all - the next row added in the DB should have an intact auto incremented value.

Thanks.

EDIT: losing the link with other table records on this PK is not an issue for this row. We can restore it manually.

4

1 回答 1

23

不一定推荐,但插入要更改数字的行的副本,但使用所需的 ID:

SET IDENTITY_INSERT aTable ON
GO

-- Attempt to insert an explicit ID value of 3
INSERT INTO aTable (id, product) VALUES(3, 'blah')       
GO

SET IDENTITY_INSERT aTable OFF
GO

然后删除带有您不想要的数字的行(在您更新任何 FK 引用之后)。

更多详细信息:http ://technet.microsoft.com/en-us/library/aa259221(v=sql.80).aspx


为了后代,为了澄清下面评论中的问题,只有当您插入一个大于当前最大值的值时,自动增量值才会受到影响。

引用链接文章:

如果插入的值大于表的当前标识值,SQL Server 会自动使用新插入的值作为当前标识值。

于 2013-09-19T08:13:05.540 回答