2012-06-13 57 views
2

我需要将csv文件中的数据插入到临时表中,并在另一个表中插入一些用于相应id值的数据。我已经创建并将数据插入到csv文件中。对于csv文件中的所有记录,我如何循环并在其他表格中插入相应记录的球形数据。遍历一个临时表并插入到另一个表

CREATE TABLE #tbcompanies 
(ID INT) 
GO 

BULK 
INSERT #tbcompanies 
FROM 'd:\ids.csv' 
WITH 
(
ROWTERMINATOR = '\n' 
) 

select * from #tbcompanies 

drop table #tbcompanies 
+0

为什么你认为一个循环是必要的吗?你不能只是'INSERT [其他表] SELECT ID FROM #tbcompanies AS t/*也许有人加入[另一个表]'? –

回答

6

假设两个表有一个ID列,您可以更新其他表所示:

update ot 
set  col1 = tmp.col1 
.  col2 = tmp.col2 
from @tbcompanies tmp 
join OtherTable ot 
on  ot.ID = tmp.ID 

如果除了更新,你想不存在insert行,考虑merge statement

; merge OtherTable as target 
using #tmpcompanies as source 
on  target.id = source.id 
when not matched by target then 
     insert (id, col1, col2) values (source.id, source.col1, source.col2) 
when matched then 
     update set col1 = source.col1, col2 = source.col2; 
+0

谢谢,我实际上需要插入一些新的记录。我会更新我的脚本。 – Joshua

1

你不通过任何需要循环,因为你使用SQL Server 2008和该版本支持MERGE统计EMENT。

看一看here

或者只是使用更新与from子句并加入这两个表。

1

如果您需要的是upsert功能,我强烈建议您使用Merge功能。

伪代码

merge TargetTableName target 
    using #tbcompanies tmp on tmp.idfield=target.idfield 
    when matched then update...... 
    when not matched then insert........... 
相关问题