關(guān)于Update在不同數(shù)據(jù)庫的使用
作者:shoushou2001
SQL語法難嗎?其實不難。但是也有忘記的可能,因此作者將它寫下來,以備不時之需。現(xiàn)在分享給大家,一起來看看吧。
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后)
綜上,更新多個字段,有兩種寫法,分別是
- update tname set (a1, a2...)=(select a1, a2...from...)--DB2寫法
- --------------------華麗分割線----------
- update tname set a1=b.a2, a2=b.a2...from b... --mssql 寫法
Oracle下面跟db2差不多,環(huán)境沒搭建好,就不測試了,要用的時候再參考以上兩種寫法.
簡單在mysql下測試,結(jié)果如下,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
原文鏈接: http://shoushou2001.iteye.com/blog/1110350
【編輯推薦】
責(zé)任編輯:艾婧
來源:
Java place