微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

mysql实现oracle存储过程默认参数

我们都知道oracle存储过程支持为参数设置认值,这样即使存储过程升级,原来的调用也可以不受影响。但是MysqL不支持,mariadb也没有支持(截止10.4也是如此)。但是这一限制会导致升级麻烦重重。虽然如此,我们可以通过MysqL 5.7/mariadb 10.2引入的json类型来变通实现。如下所示:

drop function number_stats;
CREATE FUNCTION number_stats(in_numbers JSON)
    RETURNS INTEGER
    NOT DETERMINISTIC
    CONTAINS sql
    COMMENT 'Accept an array of integers and their median'
BEGIN
    DECLARE v_count INT UNSIGNED
        DEFAULT JSON_LENGTH(in_numbers);
    RETURN JSON_EXTRACT(
        in_numbers,
        CONCAT('$[', FLOOR(v_count / 2), ']')
    );
END;

 

mariadb> select number_stats('[1,2,3,4]');

+---------------------------+
| number_stats('[1,2,3,4]') |
+---------------------------+
|                         3 |
+---------------------------+
1 row in set

mariadb> select JSON_VALUE('{ "x": [0,1], "y": "[0,1]", "z": "Monty" }','$.z');
+----------------------------------------------------------------+
| JSON_VALUE('{ "x": [0,1], "y": "[0,1]", "z": "Monty" }','$.z') |
+----------------------------------------------------------------+
| Monty                                                          |
+----------------------------------------------------------------+
1 row in set

mariadb> select JSON_VALUE('{ "x": [0,1], "y": "[0,1]", "z": "Monty" }','$.x
');
+----------------------------------------------------------------+
| JSON_VALUE('{ "x": [0,1], "y": "[0,1]", "z": "Monty" }','$.x') |
+----------------------------------------------------------------+
| NULL                                                           |
+----------------------------------------------------------------+
1 row in set

mariadb> select JSON_VALUE('{ "x": [0,1], "y": "[0,1]", "z": "Monty" }','$.y
');
+----------------------------------------------------------------+
| JSON_VALUE('{ "x": [0,1], "y": "[0,1]", "z": "Monty" }','$.y') |
+----------------------------------------------------------------+
| [0,1]                                                          |
+----------------------------------------------------------------+
1 row in set

https://federico-razzoli.com/variable-number-of-parameters-and-optional-parameters-in-MysqL-mariadb-procedures

https://mariadb.com/kb/en/library/json_extract/

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐