AliSQL提供returning功能,支持DML語句返回Resultset,同時提供了工具包(DBMS_TRANS)便于您快捷使用。

背景信息

MySQL的語句執行結果報文通常分為三類:Resultset、OK和ERR。針對DML語句返回的是OK或ERR報文,其中包括影響記錄、掃描記錄等屬性。但在很多業務場景下,執行INSERT、UPDATE、DELETE這樣的DML語句后,都會跟隨SELECT查詢當前記錄內容,以進行接下來的業務處理,為了減少一次客戶端和服務器的交互,returning功能支持使用DML語句后返回Resultset。

前提條件

實例版本為RDS MySQL 8.0。

語法

DBMS_TRANS.returning(<Field_list>,<Statement>);

參數說明如下。

參數 說明
Field_list 期望的返回字段,多個字段以英文逗號(,)進行分隔,支持表中原生的字段或星號(*),不支持進行計算或者聚合等操作。
Statement 執行的DML語句,支持INSERT、UPDATE、DELETE。

注意事項

dbms_trans.returning()不是事務性語句,會根據DML語句來繼承事務上下文,結束事務需要顯式的提交或者回滾。

INSERT Returning

針對INSERT語句,returning返回插入到表中的記錄內容。

示例:

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)
說明
  • 如果沒有填入Field_list,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 asinsert select形式的則不支持。
    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)