mysql實現oracle存儲過程默認參數

咱們都知道oracle存儲過程支持爲參數設置默認值,這樣即便存儲過程升級,原來的調用也能夠不受影響。可是mysql不支持,mariadb也沒有支持(截止10.4也是如此)。可是這一限制會致使升級麻煩重重。雖然如此,咱們能夠經過mysql 5.7/mariadb 10.2引入的json類型來變通實現。以下所示:mysql

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-proceduressql

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

相關文章
相關標籤/搜索