SQL 用update语句一次更新多个字段应该怎么写?

cgl4134 2012-08-19 12:15:11
例如:
a,b,c 是表t的3个字段,通过 条件1 和 条件2 可以分别定位到一条记录

select a,b,c from t where 条件1
select a,b,c from t where 条件2

现在想把条件2 对应的记录分别修改位条件1对应的记录

update t set a =(select a from t where 条件1),b=(select b from t where 条件1),c=(select c from t where 条件1) where 条件2

有木有简单点的写法.. 譬如

update t set (a,b,c)=(select a,b,c from t where 条件1) where 条件2

求SQL大婶
...全文
393045 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
心弄影 2014-06-29
  • 打赏
  • 举报
回复
一次性该一行记录的,多个字段: 错误实例: update tb_name set (id,name,sex)=(1,'asd','男') where 条件2 正确实例: update tb_name set id=1,name='asd',sex='男' where 条件2
skhaoren 2012-08-20
  • 打赏
  • 举报
回复
楼上很详细了。我没什么要补充了
叶子 2012-08-19
  • 打赏
  • 举报
回复

--> 测试数据: @A
declare @A table (id int,c1 varchar(1),c2 varchar(1),c3 varchar(1))
insert into @A
select 1,'a','b','c' union all
select 2,'d','e','f' union all
select 3,'g','h','i'

--> 测试数据: @B
declare @B table (id int,c1 varchar(1),c2 varchar(1),c3 varchar(1))
insert into @B
select 4,'j','k','l' union all
select 5,'m','n','o' union all
select 6,'p','q','r' union all
select 7,'s','t','u'

--例如更新@A的第二条变成@B的id=6的数据
update @A
set c1=b.c1 ,c2=b.c2,c3=b.c3
from @A a,@B b where a.id=2 and b.id=6

select * from @A
/*
id c1 c2 c3
----------- ---- ---- ----
1 a b c
2 p q r
3 g h i
*/


昵称被占用了 2012-08-19
  • 打赏
  • 举报
回复
update a set
a = b.a
,b=b.b
,c=b.c
from t a,t b
where (a.条件1) and (b.条件2)
  • 打赏
  • 举报
回复
楼上都写完了
以学习为目的 2012-08-19
  • 打赏
  • 举报
回复 4

--try
UPDATE a
SET a = b.a,
b = b.b,
c = b.c
FROM t a,
t b
WHERE (a.条件1)
AND (b.条件2)
xxjltan 2012-08-19
  • 打赏
  • 举报
回复
+1[Quote=引用 1 楼 的回复:]

SQL code
update a set
a = b.a
,b=b.b
,c=b.c
from t a,t b
where (a.条件1) and (b.条件2)
[/Quote]

22,294

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧