我怎样在 MSSQL 中覆盖 identity
列?我尝试了:
SET IDENTITY_INSERT GeoCountry ON
UPDATE GeoCountry SET CountryID = 18 WHERE CountryID = 250
但是我得到了以下结果:
第二行:无法更新标识列'CountryID'。
我怎样在 MSSQL 中覆盖 identity
列?我尝试了:
SET IDENTITY_INSERT GeoCountry ON
UPDATE GeoCountry SET CountryID = 18 WHERE CountryID = 250
但是我得到了以下结果:
第二行:无法更新标识列'CountryID'。
identity_insert
设置为ON,并将要更新的行复制到一个新的具有新ID值的行中,然后删除旧行(假设没有任何外键引用该行)。set identity_insert GeoCountry on
go
insert into GeoCountry (all columns including IDentity column)
select 18, (all columns except IDentity column)
from GeoCountry where CountryID = 250
-- Delete will only work if no referencing FK's
delete GeoCountry where CountryID = 250
set identity_insert GeoCountry off
go
[鉴于你试图更新它,这说明它仍在使用中(即通过引用FK),这使事情变得更加复杂...]在SQL Server中,无法更新身份列。您必须删除原始记录,然后使用身份值插入记录,因为没有支持更新身份值的功能。
打开[ColumnName]标识插入 插入先前存储在该记录中的标识和其他信息 关闭[ColumnName]标识插入
如果你想要更新一个身份列,这里提供一种可能的方法:
使用 SELECT IDENT_CURRENT('<table name>')
来查看当前表中存在的最高 id。
set identity_insert [dbo].[MyTableName] on
delete from [dbo].[MyTableName]
output
<new-id-value-here>,
[deleted].[Col1],
[deleted].[Col2],
[deleted].[Col3],
into
[dbo].[MyTableName] (
[IdColumnName],
[Col1],
[Col2],
[Col3])
where
[IdColumnName]=<old-id-value-here>
set identity_insert [dbo].[MyTableName] off
如果您想重新枚举标识字段的值,因为例如这些值已经混乱了,只需按照以下步骤操作:
在设计模式下打开表格
单击“标识规范”
将“(是标识)”标记为“否”
(您的标识字段仍然是主键)
关闭并保存设计
在编辑模式下打开表格
根据需要更改标识字段的值
(只需注意不能有重复值)
关闭表格,再次在设计模式下打开它
将标识字段(是标识)替换为“是”
关闭表格,完成。