以下为测试例子。
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来对应。
多表关联同时更新多条不同的记录方法说明
以下为测试例子。 1.首先创建两张临时表并录入测试数据: 复制代码 代码如下: create table #temptest1 ( id int, name1 varchar(50), age int ) create table #temptest2 ( id int, name1 varchar(50), age int ) 查询出此时的表数据为: #temptest1 #temp
本文来自网络,不代表站长网立场,转载请注明出处:https://www.tzzz.com.cn/html/jc/mssql/2021/1224/42795.html