ta
id a b c
1 11 12 13
2 21 22 23
3 31 32 33
4 41 42 43
5 51 52 53
tb
id a b c
1 111 12 13
2 21 222 23
3 31 32 333
4 41 42 43
5 555 52 53
以上是两张表、、如何写一个存储过程
将tb中的数据更新为ta的数据
在线等
急急急急急急急急。。。。。。。。。。。。。
存储过程
------解决方案--------------------
你有什么条件吗?没有条件用一条sql语句就可以了
update b
set a=a.a,b=a.b,c=a.c
from tb b
inner join ta a on a.id=b.id
------解决方案--------------------
delete from b
insert into b
select * from a
------解决方案--------------------
create proc change
as
begin
update ta set ta.a =tb.a,
ta.b=tb.b,
ta.c=tb.c
from tb
where ta.id=tb.id and tb.id in(select id from ta)
end
你试试
------解决方案--------------------
--如果批量更新数据,推荐使用MERGE,无论是INSERT还是UPDATE,从执行之间上看,MERGE INTO(MERGE)都要比直接INSERT/UPDATE的效率高;
create table ta(id int,a int,b int,c int)
create table tb(id int,a int,b int,c int)
insert into ta values (1,11,12,13)
insert into ta values (2,21,22,23)
insert into ta values (3,31,32,33)
insert into ta values (4,41,42,43)
insert into ta values (5,51,52,53)
insert into tb values (1,111,12,13)
insert into tb values (2,21,222,23)
insert into tb values (3,31,32,333)
insert into tb values (4,41,42,43)
insert into tb values (5,555,52,53)
--insert into tb values (6,61,666,63)
select * from ta --ta 目标表
select * from tb --tb 源表
--如果需要存储过程,将以下代码封装到存储过程即可。
-- CREATE PROCEDURE SP_TABLE_DATE_MERGE
--AS
--BEGIN
merge ta using tb
on(ta.id=tb.id)
when matched then update set ta.a=tb.a , ta.b=tb.b , ta.c=tb.c -- 匹配的时候,更新
when not matched then INSERT VALUES(tb.id,tb.a,tb.b,tb.c) -- 源表有,目标表没有,插入
WHEN not matched BY SOURCE THEN DELETE; -- 目标表有,源表没有,目标表该数据删除(会删除目标表数据,慎用!)