Sql server 的update语句的新认识

来源:互联网 发布:客观评价张学良知乎 编辑:程序博客网 时间:2024/05/17 06:20

一般的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

原创粉丝点击