sql server update多个字段(可以通过一个子查询更新多字段)

1、update 语句使用别名

我们通常的update语句是这样写的:

update table set coumn1 = value1 where column2 = "test";

如果我们想用别名的话,我们会这样去写:

update table t set t.coumn1 = value1 where t.column2 = "test";

但是这样是会报错的,正确的写法是这样的: 

update t set t.column1 = value1 from table t where t.column = 'test';

2、更新多个字段

我们都知道update 语句更新多个字段的写法是这样的:

update table set coumn1 = value1,coumn2 = value2  where column2 = "test";

或者

update t set t.column1 = value1,t.column2 = value2 from table t where t.column = 'test';

但是有这样的一个场景: 我们要更新的一个表的多个字段,这几个在字段的值都需要子查询来获得,且子查询的写法都是一样的,往往实现需要这样去写:

update table set coumn1 = (select value1 from tableb d where table.column3= d.columnx)

                          coumn2 = (select value2 from tableb d where table.column3= d.columnx)

where column2 = "test";

子查询都是一样的,我们却得写多次,所以我们可以这样去写:

update t set t.coumn1 = d.value1,t.colum2 = d.value2

    from table t 

      left join tableb d on t.column3 = d.columnx

      where  t.column2 = "test";

以上写法和结论均在Microsoft SQL Server 2016 (SP1)上得出,如果有误,请帮忙指出,希望可以帮到你。

我开了自己的公众号,希望你可以关注支持一下,谢谢!

 

  • 17
    点赞
  • 50
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值