我需要将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发布于 2012-06-13 20:18:29
假设两个表都有一个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;发布于 2012-06-13 20:19:56
您不需要遍历任何内容,因为您使用的是SQL Server2008,并且此版本支持MERGE语句。
看一下here。
或者简单地使用带有from子句的update并连接这两个表。
发布于 2012-06-13 20:21:05
如果需要upsert功能,我强烈推荐使用Merge函数。
伪码
   merge TargetTableName target
   using #tbcompanies tmp on tmp.idfield=target.idfield
   when matched then update......
   when not matched then insert...........https://stackoverflow.com/questions/11014612
复制相似问题