求SqL语句,根据另一表批量更改数据
如下有两表
A B
ID Location ID NewLocation
1 a 2 d
2 b 3 d
3 c 4 e
4 d 6 e
5 e
6 f
按B中的数据更改A表的Location字段,让与B表中ID相对应的A表的Location换成B表中的NewLocation
更新后A表变为:
A
ID Location
1 a
2 d
3 d
4 e
5 e
6 e
------解决方案--------------------update a
set location = b.newlocation
from a,b
where a.id = b.id
------解决方案--------------------update A set A.Location=B.NewLocation FROM A inner join B on A.ID=B.ID
------解决方案--------------------if object_id( 'pubs..A ') is not null
drop table A
go
create table A(ID int,Location varchar(1))
insert into A(ID,Location) values(1, 'a ')
insert into A(ID,Location) values(2, 'b ')
insert into A(ID,Location) values(3, 'c ')
insert into A(ID,Location) values(4, 'd ')
insert into A(ID,Location) values(5, 'e ')
insert into A(ID,Location) values(6, 'f ')
go
if object_id( 'pubs..B ') is not null
drop table B
go
create table B(ID int,newLocation varchar(1))
insert into B(ID,newLocation) values(2, 'd ')
insert into B(ID,newLocation) values(3, 'd ')
insert into B(ID,newLocation) values(4, 'e ')
insert into B(ID,newLocation) values(6, 'e ')
update a
set location = b.newlocation
from a,b
where a.id = b.id
select * from A
drop table A,B
/*
ID Location
----------- --------
1 a
2 d
3 d
4 e
5 e
6 e
(所影响的行数为 6 行)
*/
------解决方案--------------------