设为首页 - 加入收藏 ASP站长网(Aspzz.Cn)- 科技、建站、经验、云计算、5G、大数据,站长网!
热搜: 数据 创业者 手机
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

多表关联同时更新多条不同的记录方法说明

发布时间:2021-12-24 09:45 所属栏目:116 来源:互联网
导读:以下为测试例子。 1.首先创建两张临时表并录入测试数据: 复制代码 代码如下: create table #temptest1 ( id int, name1 varchar(50), age int ) create table #temptest2 ( id int, name1 varchar(50), age int ) 查询出此时的表数据为: #temptest1 #tempte
以下为测试例子。
1.首先创建两张临时表并录入测试数据:
复制代码 代码如下:
 
 
create table #temptest1
(
id int,
name1 varchar(50),
age int
)
create table #temptest2
(
id int,
name1 varchar(50),
age int
)
 
 
查询出此时的表数据为:
 
#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。
 
如何一次性更新多条不同值的记录
标题可能没说清楚,假设有这样两张表:
 
复制代码 代码如下:
 
 
create table testA(
id number,
eng varchar2(3),
chi varchar2(3)
)
create table testB(
id number,
eng varchar2(3),
chi varchar2(3),
anythingother varchar2(1)
)
 
 
现有记录
testA:
ID ENG CHI
===============
1 a 一
2 b 二
3 c 三
testB:
ID ENG CHI ANY....
=================
1 d 四
2 e 五
3 f 六
我想把testB中的记录的ENG,CHI字段更新到testA中去,以ID来对应。

(编辑:ASP站长网)

    网友评论
    推荐文章
      热点阅读