两个表数据合并的问题,请高手指点,谢谢!
有两个表,结构完全一样,当然在不同的库里。
机构为:ypxh1(bm int,mc varchar(80),gg varchar(20),dw char(10),dj money,sl int,je money);
ypxh2(bm int,mc varchar(80),gg varchar(20),dw char(10),dj money,sl int,je money)
但是,两个表的数据不完全一样,现在我想要做的是:
把表ypxh2的数据合并到ypxh1,如果两个表bm的值相同,那么字段sl和je的值相加,否则就向ypxh1插入记录。
[解决办法]
insert into db1.dbo.ypxh1 select y2.* from db2.dbo.ypxh2 y2 left outer join db1.dbo.ypxh1 y1 on y2.bm=y1.bm where y1.bm is null;
[解决办法]
update db1.dbo.ypxh1
set db1.dbo.ypxh1.sl=db1.dbo.ypxh1.sl+db2.dbo.ypxh2.sl,
db1.dbo.ypxh1.je=db1.dbo.ypxh1.je+db2.dbo.ypxh2.je
from db2.dbo.ypxh2
where db1.dbo.ypxh1.bm=db2.dbo.ypxh2.bm;
[解决办法]
如果上述两个数据库在同一个服务器上,上述方法可行。
否则,请考虑用连接服务器,方法参见:
http://community.csdn.net/Expert/TopicView3.asp?id=5224107
[解决办法]
--try
update ypxh1 set sl=sl+ypxh2.sl, je=je+ypxh2.je
from (select bm, sl=sum(sl), je=sum(je) from ypxh2 group by bm) as ypxh2
where ypxh2.bm=ypxh1.bm
insert ypxh1
select * from ypxh2 where bm not in(select distinct bm from ypxh1)
[解决办法]
是要两步的
[解决办法]
一步无法完成。
[解决办法]
用游标吧。^_^。
[解决办法]
update ypxh1 set sl=sl+ypxh2.sl, je=je+ypxh2.je
from (select bm, sl=sum(sl), je=sum(je) from ypxh2 group by bm) as ypxh2
where ypxh2.bm=ypxh1.bm
这样使sl和je成十倍的增加,不对。
update db1.dbo.ypxh1
set db1.dbo.ypxh1.sl=db1.dbo.ypxh1.sl+db2.dbo.ypxh2.sl,
db1.dbo.ypxh1.je=db1.dbo.ypxh1.je+db2.dbo.ypxh2.je
from db2.dbo.ypxh2
where db1.dbo.ypxh1.bm=db2.dbo.ypxh2.bm;
这个脚本比较和实际相符。
----------------------------------------------
bm是不是有重复的?
如果有重复的话,自己就要考虑是不是修改合并的规则了
[解决办法]
按照楼主的描述,下面这句才是对的
---------------------------------------------------
update ypxh1 set sl=sl+ypxh2.sl, je=je+ypxh2.je
from (select bm, sl=sum(sl), je=sum(je) from ypxh2 group by bm) as ypxh2
where ypxh2.bm=ypxh1.bm