2012-10-02 109 views
6
CREATE TABLE TestTable (id int IDENTITY (1,1), name nvarchar(100)); 
INSERT INTO TestTable(name) VALUES ('data1');      
INSERT INTO TestTable(name) VALUES ('data2');      
Declare @Identity as int 
set @identity=IDENT_CURRENT ('TestTable') 
SET IDENTITY_INSERT TestTable ON; 

我如何實現此功能?用Identity_Insert插入數據是ON並插入到Table1中從表2中選擇*

INSERT INTO TestTable 
Select * from 
(
Select 55 as a,'data55' as b 
Union 
Select 56 as a,'data55' as b 
)n 

當這種被替換然後.. 消息8101,級別16,狀態1,行7 當使用列列表只能指定表「TestTable的」標識列的顯式值和IDENTITY_INSERT已打開。

INSERT INTO TestTable (id, name) VALUES (55, 'data55');  
INSERT INTO TestTable (id, name) VALUES (56, 'data55');  

SET IDENTITY_INSERT TestTable OFF; 
DBCC CHECKIDENT (TestTable, reseed,@identity) 
INSERT INTO TestTable(name) VALUES ('data3');     
Select * from TestTable 
Drop table TestTable 
+4

再次閱讀錯誤消息:「...只能在使用列列表**和** IDENTITY_INSERT爲ON時指定。」。在你的聯合示例中,你不提供列列表。 –

回答

8

你需要說

INSERT INTO TestTable (id, name) 
Select * from 
( 
Select 55 as a,'data55' as b 
Union 
Select 56 as a,'data55' as b 
)n 
+1

其工作正常,但我的要求是INSERT INTO TestTable 選擇* from ... –

+5

我的要求是法拉利和該國的豪宅。這並不影響語言的規則。 – podiluska

+0

我犯了一個基本的錯誤,並多次忽略它:( –

5

這應該正常工作:

SET IDENTITY_INSERT TestTable ON; 

INSERT INTO TestTable(id, name) 
Select * 
from 
( 
    Select 55 as a, 'data55' as b 
    Union 
    Select 56 as a, 'data55' as b 
)n; 

剛剛成立SET IDENTITY_INSERT ONINSERT子句中列出的字段。

相關問題