关于update在不同数据库的使用

sql语法虽然简单,但也有忘记的可能,写下来,以备不时之需。

 

1、单表更新多个字段
DB2:
    update t1 set (id, name)=('1','2') where name like 'kiss%'--正确运行

 

    update t1 set id='1',name='2' where name like  'kiss%'--正确运行

 

MSSQL:


    update t1 set (id, name)=('1','2') where name like 'kiss%'----报: '(' 附近有语法错误。

 

    update t1 set id='1',name='2' where name like  'kiss%'--正确运行

 

2、多表连合更新


DB2:
      update t1 set id=(select id from t2 where t2.name like  'kiss%'--正确运行

     

     update t1 set (id,name)=(select id,name from t2 where t2.name like  'kiss%'--正确运行

    

     update t1 a set id=b.id from t2 b where b.id='dkdkd'--sql遇到非法符号

 

MSSQL:(update tablename 别名,这种写法是不对的)
 

    update t1 set id=b.id, bid=b.bid from t2 b where b.bid='dkdkd' --正确运行
 
    如果要用别名,则也要把t1放在from后面

   update a set a.id=b.id, a.bid=b.bid from t1 a, t2 b where a.id=b.id and b.bid='dkdkd' --正确运行(别名放在from后)

 

综上,更新多个字段,有两种写法,分别是

1、update tname set (a1, a2...)=(select a1, a2...from...)--DB2写法
2、update tname set a1=b.a2, a2=b.a2...from b...   --mssql 写法

 

Oracle下面跟db2差不多,环境没搭建好,就不测试了,要用的时候再参考以上两种写法.

 

简单在mysql下测试,结果如下,mysql与mssql都支持 set a1=b.a2, a2=b.a2...from b. 的写法

 

mysql> update order2 set id=1,price=2 where ordernum='kdkdk'
    -> ;
Query OK, 0 rows affected (0.00 sec)
Rows matched: 0  Changed: 0  Warnings: 0

mysql> update order2 set (id, price)=(1,2) where ordernum='dkdkd'
    -> ;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near '(id,
price)=(1,2) where ordernum='dkdkd'' at line 1
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值