MySQL 对于 statement 执行结果报文通常分为两类 Resultset 和 OK/ERR,针对 DML 语句则返回OK/ERR 报文,其中包括几个影响记录,扫描记录等属性。但在很多业务场景下,INSERT/UPDATE/DELETE 这样的DML语句后,通常都会跟随 SELECT 查询当前记录内容,以进行接下来的业务处理, 为了减少一次 Client <-> DB Server 交互,类似 PostgreSQL / Oracle 都提供了 returning clause 支持 DML 返回 Resultset。
AliSQL 为了减少对 MySQL 语法兼容性的侵入,并支持 returning 功能, 采用了 native procedure 的方式,使用DBMS_TRANS package,统一使用 returning procedure 来支持 DML 语句返回 Resultset。
DBMS_TRANS.returning(Field_list=>, Statement=>);
例如:
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)
*请左右滑动阅览
mysql> call dbms_trans.returning("", "insert into t select * from t");
ERROR 7527 (HY000): Statement didn't support RETURNING clause
例如:
*请左右滑动阅览
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)
例如:
*请左右滑动阅览
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)
点击“阅读原文”
解锁RDS MySQL版更多信息
阿里巴巴数据库技术
微信:alibabadba
分享数据库前沿
解构实战干货
长按二维码关注