2010-10-16 78 views
28

如何覆蓋MSSQL中的標識列?我想:更新標識列中的值

SET IDENTITY_INSERT GeoCountry ON 
UPDATE GeoCountry SET CountryID = 18 WHERE CountryID = 250 

但我拿回

Line 2: Cannot update identity column 'CountryID'. 

回答

55

您試圖執行更新,而不是插入新行。

爲了做到這一點,你將需要設置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 

[既然你要更新它,那就表明它仍然在使用(通過引用FK的IE),這讓事情變得更加複雜... ]

+0

這太冗長了。對於一個簡單的「你不行」的太多解釋。你需要重新插入新的身份。 – 2017-02-06 08:24:51

+5

@Amir男:不正確。 – 2017-02-06 11:21:17

10

您無法更新SQL Server中的標識列。您必須刪除原始記錄,然後插入具有標識值的記錄,因爲不支持更新標識值。

SET IDENTITY_INSERT [的ColumnName]在 插入的身份和以前存儲在該記錄 集的附加信息IDENTITY_INSERT [的ColumnName]關

+2

+1 IMO這是正確的答案。當提出「我如何更新身份值」這個問題時,這是一個非常重要的細節,您實際上無法更新該值,但必須刪除並重新插入。被接受的答案在這方面失敗了。 – alan 2015-09-03 20:40:12

10

如果你想更新在這裏的身份列是一個可行的方法:

  • 在SQL Server Management Studio中,打開在設計視圖中的表,禁用「標識規範>是一種身份」在列
  • 執行更新
  • 啓用列

做一個SELECT IDENT_CURRENT('<table name>'),看它是否返回當前存在於表中的最高ID「標識規範>是一種身份」。

+0

這種方法是更好的方法,如果你有外部級聯更新的外鍵,因爲你得到「免費」的更新。 – Jacob 2014-07-02 22:59:44

-1

您無法更新現有標識列。但是,這是我使用的解決方法:

-- create copy of the existing table 
SELECT * INTO old_tablename FROM tablename 

-- delete everything in the original table 
DELETE FROM tablename 

-- temporarily allow updating identity columns 
SET IDENTITY_INSERT tablename ON; 

-- copy data into the existing table from the copy of the existing table 
-- modify the select statement to put whatever you want in the identity column 
-- of course you can join to other tables etc to get the int for your id column 
INSERT INTO tablename (
    id_column, 
    column2, 
    column3 
) SELECT 
    old_id, 
    column2, 
    column3 
FROM old_tablename; 

-- prevent updating identity columns in future 
SET IDENTITY_INSERT tablename OFF; 

-- drop the copied table once you've tested that everything worked ok 
-- DROP TABLE old_tablename 
+0

DELETE如果級聯刪除已打開,則從表名刪除所有關係。如果你根本沒有任何關係,這是可行的,但是爲了更新一些記錄而刪除整個表並不是一件好事。 – ManOVision 2017-09-13 22:25:37