2013-03-07 82 views
0

我有一個具有強制自動增量列的表。但有些時候我必須明確地插入值。爲此我設置的身份上,但它不幹活如何在沒有自動遞增ID列的情況下插入行

下面是代碼:

SET IDENTITY_INSERT [menu_code] on 

INSERT INTO [dbo].[menu_code] 
VALUES('', '', '', '', '', 
     1 -- Auto Generated Identity column 
     ,'', '') 
+0

**如何**它是*不工作*?你有錯誤嗎?如果是這樣的話:**什麼**錯誤?你只是沒有得到你的表中的任何數據? – 2013-03-07 06:15:57

+0

表'dbo.menu_code'中的標識列的顯式值只能在使用列列表並且IDENTITY_INSERT爲ON時指定 – 2013-03-07 06:17:26

+0

由於我在 – 2013-03-07 06:18:07

回答

3

錯誤消息是水晶的問題的原因顯而易見:

一個明確的表'dbo.menu_code'中標識列的值只能在使用列列表時指定和IDENTITY_INSERT爲ON

您需要明確定義您試圖將值插入哪些列!

SET IDENTITY_INSERT [menu_code] ON 

INSERT INTO [dbo].[menu_code] (Col1, Col2, Col3, Col4, Col5, IdentityCol, Col6, Col7) 
VALUES('', '', '', '', '', 
     1 -- Auto Generated Identity column 
     ,'', '') 

SET IDENTITY_INSERT [menu_code] OFF 

我建議無論如何做這一切的時候 - 如果省略列(無論在INSERTSELECT報表)的列表中,你是在和自己的討厭的驚喜在路上。是的,這是一個更多的打字 - 一次,當你創建查詢 - 但它會爲你節省無數小時的頭痛,並試圖找到討厭的錯誤......只需定義你想工作的列的列表與明確,所有的時間。

更新:如果你從另一個表中插入這些值,我會HIGHLY推薦使用的列名的明確列出兩個INSERT還有SELECT

SET IDENTITY_INSERT [menu_code] ON 

INSERT INTO [dbo].[menu_code] (Col1, Col2, Col3, Col4, Col5, IdentityCol, Col6, Col7) 
    SELECT Col1, Col2, Col3, Col4, Col5, IdentityCol, Col6, Col7 
    FROM DM_LUBRICANTS.dbo.menu_code 

SET IDENTITY_INSERT [menu_code] OFF 
+0

但我直接插入像這樣 set identity_insert menu_code在 插入DM.dbo.menu_code select * from DM_LUBRICTS.dbo.menu_code – 2013-03-07 06:25:22

+0

但我直接插入這樣的設置identity_insert menu_code插入到DM.dbo.menu_code從DM_LUBRICTS.dbo.menu_code選擇* * – 2013-03-07 06:25:43

+1

@UsmanHussain:否**但** - 你**必須**明確定義列的列表在你的'INSERT'命令上。試試吧 - 它會起作用!而對於'SELECT',我也**推薦使用明確的列名稱而不是隻是'SELECT *'反正...... – 2013-03-07 06:26:12

相關問題