在一种情况下,我需要将部分数据从一个服务器复制到另一个服务器。表模式完全相同。我需要从源移动部分数据,这些数据可能在目标表中可用,也可能不可用。我认为的解决方案是,使用bcp将数据导出到文本(或.dat)文件,然后将该文件带到目的地,因为这两个文件都不能同时访问(不同的网络),然后将数据导入目的地。我需要满足一些条件:
请用最好的方法帮我。我想使用BCP with query选项来过滤数据,但是在导入时,如何绕过插入现有记录呢?如果需要的话,我该如何覆盖?
发布于 2010-04-07 04:06:17
不幸的是,BCPing到一个表是一个全部或没有交易,您不能选择行进来。
我会做的是。。。
希望这能有所帮助。
更新
工作中的(WIP)表我并不是指#temp表,您不能将BCP转换为临时表(至少如果可以的话,我会非常高兴)。
我的意思是创建一个具有相同结构的目标表的表,bcp到其中,将WIP行脚本写入目标表,然后删除WIP表。
假设使用SQL Server,您还没有说明使用什么RDBMS,如下所示(未尝试过的代码)。。。
-- following creates new table with identical schema to destination table
select * into WIP_Destination from Destination
where 1 = 0
-- BCP in the rows
BULK INSERT WIP_Destination from 'BcpFileName.dat'
-- Insert new rows into Destination
insert into Destination
Select * from WIP_Destination
where not id in (select id from Destination)
-- Update existing rows in destination
Update Destination
set field1 = w.field1,
field2 = w.field2,
field3 = w.field3,
. . .
from Destination d inner join WIP_Destination w on d.id = w.id
Drop table WIP_Destination
更新2
好的,所以你可以插入临时表,我刚刚试过了(那天我没有时间,对不起)。
关于主/细节记录的问题(我们现在从原来问题的主题出发,如果我是你,我会为这个话题打开一个新的问题,你会得到比我更多的答案)
您可以编写一个SP,它将逐步遍历要添加的新行。
因此,您正在遍历临时表中的行(这些行上有来自源数据库的原始id ),将该行插入目标表,使用SCOPE_IDENTITY获取新插入行的id。现在您有了旧的Id和新的ID,您可以创建一个insert语句,它将为类似的详细行插入语句。。。
insert into Destination_Detail
select @newId, field1, field2 . . . from #temp_Destination_Detail
where Id = @oldId
希望这能帮助你选择这个答案,即使它不是你要选择的答案:)
谢谢
带宽
https://stackoverflow.com/questions/2591893
复制相似问题