循环遍历临时表并插入另一个表

Jos*_*hua 2 sql sql-server sql-server-2008

我需要将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
Run Code Online (Sandbox Code Playgroud)

And*_*mar 6

假设两个表都有一个ID列,您可以更新另一个表,如:

update  ot
set     col1 = tmp.col1
.       col2 = tmp.col2
from    @tbcompanies tmp
join    OtherTable ot
on      ot.ID = tmp.ID
Run Code Online (Sandbox Code Playgroud)

如果除了更新之外,您还想insert要不存在的行,请考虑合并语句:

; 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;
Run Code Online (Sandbox Code Playgroud)