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