MySQL 對於 statement 執行結果報文一般分爲兩類 Resultset 和 OK/ERR,針對 DML 語句則返回OK/ERR 報文,其中包括幾個影響記錄,掃描記錄等屬性。但在不少業務場景下,一般 INSERT/UPDATE/DELETE 這樣的DML語句後,都會跟隨 SELECT 查詢當前記錄內容,以進行接下來的業務處理, 爲了減小一次 Client <-> DB Server 交互,相似 PostgreSQL / Oracle 都提供了 returning clause 支持 DML 返回 Resultset。mysql
AliSQL 爲了減小對 MySQL 語法兼容性的侵入,並支持 returning 功能, 採用了 native procedure 的方式,使用DBMS_TRANS package,統一使用 returning procedure 來支持 DML 語句返回 Resultset。sql
DBMS_TRANS.returning(Field_list=>, Statement=>);
其中:spa
Field list : 表明指望的返回字段,以 "," 進行分割,支持 * 號表達;code
Statement :表示要執行的DML 語句, 支持 INSERT / UPDATE / DELETE;繼承
INSERT Returning事務
針對 insert 語句, returning proc 返回插入到表中的記錄內容;get
例如:社區
CREATE TABLE `t` ( `id` int(11) NOT NULL AUTO_INCREMENT, `col1` int(11) NOT NULL DEFAULT '1', `col2` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`) ) ENGINE=InnoDB; mysql> call dbms_trans.returning("*", "insert into t(id) values(NULL),(NULL)"); +----+------+---------------------+ | id | col1 | col2 | +----+------+---------------------+ | 1 | 1 | 2019-09-03 10:39:05 | | 2 | 1 | 2019-09-03 10:39:05 | +----+------+---------------------+ 2 rows in set (0.01 sec)
若是沒有填入任何 Fields, returning 將退化成 OK/ERR 報文:兼容性
mysql> call dbms_trans.returning("", "insert into t(id) values(NULL),(NULL)"); Query OK, 2 rows affected (0.01 sec) Records: 2 Duplicates: 0 Warnings: 0 mysql> select * from t; +----+------+---------------------+ | id | col1 | col2 | +----+------+---------------------+ | 1 | 1 | 2019-09-03 10:40:55 | | 2 | 1 | 2019-09-03 10:40:55 | | 3 | 1 | 2019-09-03 10:41:06 | | 4 | 1 | 2019-09-03 10:41:06 | +----+------+---------------------+ 4 rows in set (0.00 sec)
注意: INSERT returning 只支持 insert values 形式的語法,相似create as, insert select 不支持, 例如:date
mysql> call dbms_trans.returning("", "insert into t select * from t"); ERROR 7527 (HY000): Statement didn't support RETURNING clause UPDATE Returning
針對 update 語句, returning 返回更新後的記錄:
例如:
mysql> call dbms_trans.returning("id, col1, col2", "update t set col1 = 2 where id >2"); +----+------+---------------------+ | id | col1 | col2 | +----+------+---------------------+ | 3 | 2 | 2019-09-03 10:41:06 | | 4 | 2 | 2019-09-03 10:41:06 | +----+------+---------------------+ 2 rows in set (0.01 sec)
注意: UPDATE returning 不支持多表 update 語句。
DELETE Returning
針對 delete 語句, returning 返回刪除的記錄前映像:
例如:
mysql> call dbms_trans.returning("id, col1, col2", "delete from t where id < 3"); +----+------+---------------------+ | id | col1 | col2 | +----+------+---------------------+ | 1 | 1 | 2019-09-03 10:40:55 | | 2 | 1 | 2019-09-03 10:40:55 | +----+------+---------------------+ 2 rows in set (0.00 sec)
注意
結束事務須要顯式的 COMMIT 或者 ROLLBACK。
本文爲雲棲社區原創內容,未經容許不得轉載。