多张表关联同时更新多条不同的记录

因为项目要求实现一次性同时更新多条不同的记录的需求,和同事讨论了一个比较不错的方案,这里供大家参考下。

以下为测试例子。

1.首先创建两张临时表并录入测试数据:

View Code
 1 create table #temptest1
2 (
3 id int,
4 name1 varchar(50),
5 age int
6 )
7
8 create table #temptest2
9 (
10 id int,
11 name1 varchar(50),
12 age int
13 )

查询出此时的表数据为:

#temptest1                 #temptest2

   

 

2.现在要将#temptest2中的年龄更新到相应的#temptest1中的年龄。

其实就是让[表1]中ID为1的年龄改成19,同时ID为2的年龄改成20。

当然这里的要求是只用一句SQL,不能用循环

结果如下:

 

实现方法如下:

Update t1 

Set t1 .age = t2.age

From  #temptest1 t1

Join #temptest2 t2

On  t1.id = t2.id

 

(补充)Sql Server 2008 Merge命令写法:

merge into #temptest1 t1
using(select age,id from #temptest2) t2
on t1.id = t2.id
when matched then
update set t1.age = t2.age

 

是不是挺有趣的Sql。

另外这里还有一篇相关的博文供大家参考:☜ Tracy ☞

-----------------------------------------------------------欢迎交流--------------------------------------------------------------

posted @ 2011-10-26 18:22  WILLPAN  阅读(832)  评论(5编辑  收藏  举报