2017-03-16 38 views
0

我試圖插入一個值爲0到已有數據的表的列中。 標識列是(1,1)。我是否需要刪除現有數據才能插入0值?將值0插入標識列

SET IDENTITY_INSERT table ON 
INSERT INTO table (id,...) Values(0,.....) 
SET IDENTITY_INSERT table OFF 

我試圖運行這個,但腳本只是掛起。

+2

腳本**掛起**?如在,它運行「永遠」沒有返回響應?如果是這樣,有趣。如果不是,如果它返回一個*錯誤消息*,則應該描述該錯誤消息(包括所有文本) –

+1

哦,太好了。編輯清楚說明問題*中的代碼從未運行過。請嘗試創建[mcve] –

+0

您想要將0插入到標識列中?爲什麼? – Andrew

回答

0

使用identity_insert時,必須指定插入的列名。

create table t (id int not null identity(1,1), col varchar(32)); 
set identity_insert dbo.t on; 
insert into dbo.t (id,col) values(0,'test'); 
set identity_insert dbo.t off; 

rextester演示:http://rextester.com/VMT42836

回報

+----+------+ 
| id | col | 
+----+------+ 
| 0 | test | 
+----+------+ 
+0

對不起,我也指定了列名 –

1

爲此,您可以使用SET IDENTITY_INSERT表上

create table #test (id int identity(1,1), val int) 

insert into #test (val) values (10),(11) 

set identity_insert #test on 

insert into #test (id, val) values (0,12) 

set identity_insert #test off 

但如果你有PK或唯一索引ID,然後在你會得到約束錯誤

+0

問題中的代碼確實打開了identity_insert。什麼,*特別*,這個答案是爲了證明它與問題中的代碼有區別嗎? –

+0

好點...如果它掛起,需要了解實際錯誤爲什麼它出現錯誤... –

0
create table #test (id int identity(0,1), val int) 
SET IDENTITY_INSERT #test ON 
INSERT INTO #test (id,val) Values(0,100) 
SET IDENTITY_INSERT #test OFF 
SELECT * FROM #test 
 
id   val 
----------- ----------- 
0   100