SqlServer两表之间:根据一个表的字段更新另一个表的字段

经百度查询到如下两种写法:

1. 写法轻松,更新效率高:
update table1
set field1=table2.field1,
field2=table2.field2
from table2
where table1.id=table2.id

2. 常规方式,种写法相当于一个 Left join, 以外面的where为更新条数,如果不加where就是所有记录

update table1
set field1=(select top 1 field1 from table2 where table2.id=table1.id)
where table1.id in (condition)
————————————————

当要更新的字段是另外两张表的结果集时,需要用到with as ,下面是我自己用到的sql:

with table1 as
(
select e.emp_id,t.health_attr_id from sys_emp e inner join sys_health_type t on e.health_type_id = t.health_type_id
)

update a
set [health_attr_id] = b.[health_attr_id]
 from dept_emp_time a
inner join table1 b
on a.emp_id = b.emp_id 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值