2013-12-20 66 views
0

我想知道我应该使用什么样的SQL Server,Table1中的foreach记录在Table2和Table3中插入数据?

temp Table1(15 columns + ID_autoinc)通过数据进行迭代并插入实际

Table2(10 colums + ID_autoinc) and real Table3(6 columns + ID_autoinc)? 

每个记录也同时在表2中插入数据,我需要身份将其插入到表3。

Conceptualy我需要:

SELECT * FROM Table1 into #TempTable1 

FOREACH-> Record in #TempTable1 { 

INSERT INTO Table2(col1 ... col10) VALUES(#TempTable1.col1 ... #TempTable1.col10) 
DECLARE @Table2Identity as int 
@Table2Identity = SCOPE_IDENTITY() 

INSERT INTO Table3(col1 ... col6) VALUES(@Table2Identity, #TempTable1.col11 ... #TempTable1.col15) 

} 
+0

什么是插入到从临时表中各表的标准是什么? 您可以使用merge.knowing样本数据和条件很重要。 – KumarHarsh

+1

不要循环。 '插入表2(col1,col2,col3)从table1'中选择col1,col2,col3。重复table3。 – Blorgbeard

+0

我更新了我的问题,即时通讯仍然不确定是否解释清楚。提前致谢。 – user1281760

回答

1

为什么你需要通过表1的数据迭代?你可以只是插上表2和表3语句从表1是SELECT,例如:

INSERT Table2(<Column1, Column2 etc) 
SELECT Col1, Col2, etc from Table1; 

和表3做同样的。在插入表2和表3之前,您没有提到要对表1中的数据执行什么处理(如果有)。

+0

我更新了问题。谢谢。 – user1281760

1

您可以声明cursor并循环遍历每行,但它比需要的更慢,更复杂成为。

我不认为你实际上也需要临时表。

如果有表2中没有什么是当前,那么就这样做:

insert into Table2 (col1, col2, ..) 
select col1, col2, .. 
from Table1 

insert into Table3 (ID, col1, col2, ..) 
select ID, col1, col2, .. 
from Table2 

需要注意的是,如果你想插入它Table3.ID不能为identity列。

如果表2已经有一些数据,你应该能够做这样的事情:

begin transaction 

declare @oldId int = select isnull(max(ID),0) from Table2 

insert into Table2 (col1, col2, ..) 
select col1, col2, .. 
from Table1 

insert into Table3 (ID, col1, col2, ..) 
select ID, col1, col2, .. 
from Table2 
where ID > @oldID 

commit 
2
MERGE Table2 AS target 
using (select all column from table1 )) as source 
on 0=1 
WHEN NOT MATCHED then 
INSERT (column name of table2) --table2 
     VALUES (mention those column from source which need to insert int table2) --those 
OUTPUT inserted.id,mention those column from source which need to insert int table1 INTO DetailsTable; 
--inserted.id is that id of table2 that will be inserted in table2 

尝试,并要求

相关问题