`
shoushou2001
  • 浏览: 32771 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

关于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
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics