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

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


当前回答

您可以使用以下代码创建一个新表。

SELECT IDENTITY (int, 1, 1) AS id, column1, column2
INTO dbo.NewTable
FROM dbo.OldTable

然后删除旧的db,并将新db重命名为旧db的名称。注意:columnn1和column2表示旧表中希望保留在新表中的所有列。

其他回答

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

例子:

SET IDENTITY_INSERT dbo.Tool ON
GO

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

您不能更新标识列。 SQL Server不允许更新标识列,这与使用更新语句更新其他列不同。

尽管有一些替代方案可以实现类似的需求。

当需要为新记录更新标识列值时

使用DBCC CHECKIDENT检查表的当前标识值,如果需要,则更改标识值。

DBCC CHECKIDENT('tableName', RESEED, NEW_RESEED_VALUE)

当需要更新现有记录的标识列值时

使用IDENTITY_INSERT,它允许显式的值插入到表的标识列中。

SET IDENTITY_INSERT YourTable {ON|OFF}

例子:

-- Set Identity insert on so that value can be inserted into this column
SET IDENTITY_INSERT YourTable ON
GO
-- Insert the record which you want to update with new value in the identity column
INSERT INTO YourTable(IdentityCol, otherCol) VALUES(13,'myValue')
GO
-- Delete the old row of which you have inserted a copy (above) (make sure about FK's)
DELETE FROM YourTable WHERE ID=3
GO
--Now set the idenetity_insert OFF to back to the previous track
SET IDENTITY_INSERT YourTable OFF

你需要

set identity_insert YourTable ON

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

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

set identity_insert YourTable OFF
--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

我已经解决了这个问题,首先使用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值较高的重复行。