low*_*key 31 sql t-sql sql-server
如何覆盖MSSQL中的标识列?我试过了 :
SET IDENTITY_INSERT GeoCountry ON
UPDATE GeoCountry SET CountryID = 18 WHERE CountryID = 250
Run Code Online (Sandbox Code Playgroud)
但是我回来了
SET IDENTITY_INSERT GeoCountry ON
UPDATE GeoCountry SET CountryID = 18 WHERE CountryID = 250
Run Code Online (Sandbox Code Playgroud)
Mit*_*eat 58
您正在尝试执行更新,而不是插入新行.
为此,您需要设置identity_insert
ON 并将要更新的行复制到具有新ID值的新行,然后删除旧行(假设没有FK引用它)
有点像:
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
Run Code Online (Sandbox Code Playgroud)
[鉴于您正在尝试更新它,这表明它仍在使用中(即通过引用FK)并使事情变得更复杂......]
小智 10
您无法更新SQL Server中的标识列.您必须删除原始记录,然后使用Identity值插入记录,因为不支持更新标识值.
set Identity_Insert [ColumnName] On插入先前存储在该记录集中的标识和附加信息Identity_Insert [ColumnName] Off
Sal*_*n A 10
如果您尝试更新标识列,这里有一种可能的方法:
执行a SELECT IDENT_CURRENT('<table name>')
以查看它是否返回表中当前存在的最高ID.
您还可以使用 delete into 在一个语句中执行此操作,这具有消除复制/移动行数据的任何错误的好处,例如
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
Run Code Online (Sandbox Code Playgroud)