MySQL stored procedure with variable argument list

前端 未结 2 939
长情又很酷
长情又很酷 2021-01-04 11:45

I have made a stored procedure. I want it to filter the data by different parameters. If I pass one parameter, it should be filtered by one; if I pass two, it should be filt

2条回答
  •  轮回少年
    2021-01-04 12:12

    I found a JSON-based approach which works with the latest MySQL/MariaDB systems. Check the link below (Original Author is Federico Razzoli): https://federico-razzoli.com/variable-number-of-parameters-and-optional-parameters-in-mysql-mariadb-procedures

    Basically, you take a BLOB parameter which is actually a JSON object and then do JSON_UNQUOTE(JSON_EXTRACT(json object, key)) as appropriate.

    Lifted an extract here:

    CREATE FUNCTION table_exists(params BLOB)
        RETURNS BOOL
        NOT DETERMINISTIC
        READS SQL DATA
        COMMENT '
    Return whether a table exists.
    Parameters must be passed in a JSON document:
    * schema (optional). : Schema that could contain the table.
                           By default, the schema containing this procedure.
    * table              : Name of the table to check.
    '
    BEGIN
        DECLARE v_table VARCHAR(64)
            DEFAULT JSON_UNQUOTE(JSON_EXTRACT(params, '$.table'));
        DECLARE v_schema VARCHAR(64)
            DEFAULT JSON_UNQUOTE(JSON_EXTRACT(params, '$.schema'));
    
        IF v_schema IS NULL THEN
            RETURN EXISTS (
                SELECT TABLE_NAME
                    FROM information_schema.TABLES
                    WHERE
                        TABLE_SCHEMA = SCHEMA()
                        AND TABLE_NAME = v_table
            );
        ELSE
            RETURN EXISTS (
                SELECT TABLE_NAME
                    FROM information_schema.TABLES
                    WHERE
                        TABLE_SCHEMA = v_schema
                        AND TABLE_NAME = v_table
            );
        END IF;
    END;
    

提交回复
热议问题