例:有表A和表B,两表数据都过百万,两表数据结构一样,如下代码
Table A { id int, name nvarchar(255), description nvarchar(255), source nvarchar(255), price float, quoteTime datetime }
要实现表A数据对比表B数据,如果name,description,source都相同,更新表B的price为表A的price,且表A的引入时间要大于表B。
想了一整天,试过N多方法。
题外:linq to sql 的Update 超过1万条就会卡爆,所以放弃之。用2.0的原始SQL去执行。
个人认为最快捷方式:
1.用游标集合目标表B。
fetch next from [Cursor] into @id---id集合
2.用循环出来的单个id去找出A表name,description,source都相同的行。
3.查找出来的表A结果,quotetime倒序,取top 1的price 赋值给表B当前ID的price
4.删除查找出来表A结果的所有数据
如此循环下,表A就只剩下不相同的数据
5.插入这些不相同的数据。
只用了一次循环,就完成两表数据的更新和添加。
我是用存储过程实现,附上代码,可能更直观点
View Code
忘了,还要添加A表剩下不相同的数据到B里 insert into A select * from B
update a from a,b where a.id=b.id and a.spec=b.spec
1 declare myCursor cursor for 2 select id from [A] 3 4 open myCursor 5 declare @id sysname 6 fetch next from myCursor into @id 7 while(@@fetch_status-0) 8 begin 9 ----更新目标表的数据 10 update B set price=( 11 select top 1 A.price from A as a 12 inner join ( 13 select name,description,source,price,quoteTime 14 from B where id=@id) as b 15 on a.name=b.name 16 and a.description=b.description 17 and a.source=b.source 18 order by a.quoteTime desc) 19 where id=@id 20 21 ----删除源表的相同数据 22 delete a from A as a 23 inner join ( 24 select name,description,source,price,quoteTime 25 from B where id=@id) as b 26 on a.name=b.name 27 and a.description=b.description 28 and a.source=b.source 29 30 fetch next from myCursor into @id 31 end 32 close myCursor 33 deallocate myCursor