再问个SQL的update 问题

clubsondy 2006-08-25 02:08:54
如果我想将一个表中的某些字段的数据更新到另一个表,以关健字pd_ID为相关联,又怎样写SQL呢?

例如: A表: pd_ID name expression

1 test1 abc
2 test2 asdf
3 test3 zxcv


B表: pd_ID name expression

1 test1 qwer
2 test2 lkjh
3 test3 piuu
4 test4 uopp

我想将A表中的expression字段与B表中相关联的更新,只是更新A表中有记录的数据。
...全文
202 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
clubsondy 2006-08-25
  • 打赏
  • 举报
回复
结贴。
clubsondy 2006-08-25
  • 打赏
  • 举报
回复
谢谢,先用playwarcraft的方法解决了,后面的方法会再试试,谢谢大家了。
九斤半 2006-08-25
  • 打赏
  • 举报
回复
create table A(pd_ID int,name varchar(10),expression varchar(10))
insert A
select 1,'test1','abc' union all
select 2,'test2','asdf' union all
select 3,'test3','zxcv'
select * from A

create table B(pd_ID int,name varchar(10),expression varchar(10))
insert B
select 1,'test1','qwer' union all
select 2,'test2','lkjh' union all
select 3,'test3','piuu' union all
select 4,'test4','uopp'
select * from B

begin tran
update A set A.name=B.name,A.expression=B.expression
from A,B where A.pd_ID=B.pd_ID and A.name=B.name

--update A set name=(select name from B where pd_ID=A.pd_ID),
--expression=(select expression from B where pd_ID=A.pd_ID)

select * from A
rollback tran

drop table A,B
dba_sunny 2006-08-25
  • 打赏
  • 举报
回复
update A
set A.expression=B.expression
from A,B
where A.pd_ID=B.pd_ID and A.name=B.name
clubsondy 2006-08-25
  • 打赏
  • 举报
回复
如果要更新几个字段呢?比如有:expression,expression1,expression2.
是不是:update A set A.expression=B.expression,A.expression1=B.expression1,A.expression2=B.expression2 from B where A.pd_ID=B.pd_ID
这可以了呢?

或者是waterfirer(水清)的写法:
update b set expression=(select expression from a where a.pd_ID=b.pd_ID),expression1=(select expression1 from a where a.pd_ID=b.pd_ID) where exists(select 1 from a where a.pd_ID=b.pd_ID)呢?

waterfirer 2006-08-25
  • 打赏
  • 举报
回复
update b set expression=(select expression from a where a.pd_ID=b.pd_ID) where exists(select 1 from a where a.pd_ID=b.pd_ID)
playwarcraft 2006-08-25
  • 打赏
  • 举报
回复
update A set A.expression=B.expression from B where A.pd_ID=B.pd_ID

34,594

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧