Sql server 的update语句的新认识

一般的update语句的用法为

update test set xxx = 'xxx' where id = 'xxx'
update test set xxx = 'xxx' where id = (子查询)

除了这两种形式,但不知还有这种形式

建表语句:

create table tb1(
  id int primary key identity(1,1),
  salary int
)
GO
insert into tb1(salary) values(100)
insert into tb1(salary) values(200)
GO
create table tb2(
  id int primary key identity(1,1),
  tb1_id int references tb1(id),
  salary int
)
GO
insert into tb2(tb1_id) values(1)
insert into tb2(tb1_id) values(2)


数据库中的数据:

tb1

==================

id       salary

---------------------------------

1          100

2          200

---------------------------------

tb2

==================

id        tb1_id       salary

---------------------------------

1              1            null

2               2           null

---------------------------------

要改为的结果:

tb2

==================

id        tb1_id       salary

---------------------------------

1              1            100

2               2           200

---------------------------------

sql为:

UPDATE tb2
SET tb2.salary = tb1.salary
FROM tb2 
INNER JOIN tb1 
ON (tb2.tb1_id=tb1.id)

(ps: 只有sql server才支持这种语法,oracle中是不支持的)

这种形式非常有用,以前做跨表更新是都是用视图来做的,没想到居然可以这样。

在oracle有变通的实现方法: http://www.cnblogs.com/JasonLiao/archive/2009/12/23/1630895.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值