我有SQL Server数据库,我想改变标识列,因为它开始了 有一个大数字10010,它与另一个表相关,现在我有200条记录,我想在记录增加之前修复这个问题。

更改或重置该列的最佳方法是什么?


当前回答

我已经解决了这个问题,首先使用DBCC,然后使用插入。例如,如果你的桌子是

首先在表中设置新的当前ID Value为NEW_RESEED_VALUE

MyTable { IDCol, 可乐, colB }

    DBCC CHECKIDENT('MyTable', RESEED, NEW_RESEED_VALUE)

然后你可以使用

    insert into MyTable (colA, ColB) select colA, colB from MyTable

这将复制所有记录,但使用新的IDCol值作为NEW_RESEED_VALUE开始。然后,在删除/移动外键引用(如果有)后,可以删除ID值较高的重复行。

其他回答

--before running this make sure Foreign key constraints have been removed that reference the ID. 

--set table to allow identity to be inserted
SET IDENTITY_INSERT yourTable ON;
GO
--insert everything into a temp table
SELECT * 
INTO #tmpYourTable
FROM yourTable

--clear your table
DELETE FROM yourTable
--insert back all the values with the updated ID column
INSERT INTO yourTable (IDCol, OtherCols)
SELECT ID+1 as updatedID --put any other update logic to the ID here
, OtherCols FROM #tmpYourTable
--drop the temp table
DROP TABLE #tmpYourTable
--put identity back to normal
SET IDENTITY_INSERT yourTable OFF;
GO

你需要

set identity_insert YourTable ON

然后删除行并重新插入不同的标识。

插入完成后,不要忘记关闭identity_insert

set identity_insert YourTable OFF
SET IDENTITY_INSERT dbo.TableName ON
INSERT INTO dbo.TableName 
(
    TableId, ColumnName1, ColumnName2, ColumnName3
)
VALUES
(
    TableId_Value, ColumnName1_Value, ColumnName2_Value, ColumnName3_Value
)

SET IDENTITY_INSERT dbo.TableName OFF

当使用Identity_Insert时,不要忘记包含列名,因为sql不允许你在没有指定列名的情况下进行插入

如果你的问题答对了,你想做的是

update table
set identity_column_name = some value

让我告诉你,这不是一个简单的过程,使用它是不可取的,因为它可能有一些相关的外键。

但这里有一些步骤,请采取备份表

步骤1-选择表的设计视图

步骤2-关闭标识列

现在可以使用更新查询了。

现在重做第1步和第2步,并打开标识列

参考

您还可以使用SET IDENTITY INSERT来允许您将值插入到标识列中。

例子:

SET IDENTITY_INSERT dbo.Tool ON
GO

然后你可以在单位列中插入你需要的值。