我有SQL Server数据库,我想改变标识列,因为它开始了 有一个大数字10010,它与另一个表相关,现在我有200条记录,我想在记录增加之前修复这个问题。
更改或重置该列的最佳方法是什么?
我有SQL Server数据库,我想改变标识列,因为它开始了 有一个大数字10010,它与另一个表相关,现在我有200条记录,我想在记录增加之前修复这个问题。
更改或重置该列的最佳方法是什么?
当前回答
将您的表复制到没有标识列的新表。
select columns into newtable from yourtable
用new seed添加一个标识列到newtable,并将其作为主键
ALTER TABLE tableName ADD id MEDIUMINT NOT NULL AUTO_INCREMENT KEY
其他回答
将您的表复制到没有标识列的新表。
select columns into newtable from yourtable
用new seed添加一个标识列到newtable,并将其作为主键
ALTER TABLE tableName ADD id MEDIUMINT NOT NULL AUTO_INCREMENT KEY
如果你的问题答对了,你想做的是
update table
set identity_column_name = some value
让我告诉你,这不是一个简单的过程,使用它是不可取的,因为它可能有一些相关的外键。
但这里有一些步骤,请采取备份表
步骤1-选择表的设计视图
步骤2-关闭标识列
现在可以使用更新查询了。
现在重做第1步和第2步,并打开标识列
参考
我有类似的问题,我需要更新一些id,我所做的是(我需要增加他们10k):
set identity_insert YourTable ON
INSERT INTO YourTable
([ID]
,[something1]
,[something2]
,[something3])
SELECT
([ID] + 10000)
,[something1]
,[something2]
,[something3])
FROM YourTable
WHERE something1 = 'needs updeted id'
AND something2 = 'some other condition'
set identity_insert YourTable OFF
DELETE FROM YourTable
WHERE ID >= 'your old ID From'
AND ID <= 'Your old ID To'
就是这样。希望你能理解这个逻辑,在我的情况下,还有PK-FK键与其他表连接,这意味着我必须更新它们,在我可以从“YourTable”原始行删除之前。
我知道这个问题已经有答案了,我只是想以SQL查询为例,
--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来允许您将值插入到标识列中。
例子:
SET IDENTITY_INSERT dbo.Tool ON
GO
然后你可以在单位列中插入你需要的值。