How can I pass an “array” of values to my stored procedure?

后端 未结 7 720
悲哀的现实
悲哀的现实 2020-12-15 22:39

I want to be able to pass an \"array\" of values to my stored procedure, instead of calling \"Add value\" procedure serially.

Can anyone suggest a way to do it? am I

相关标签:
7条回答
  • 2020-12-15 23:18

    For PostgreSQL, you could do something like this:

    CREATE OR REPLACE FUNCTION fnExplode(in_array anyarray) RETURNS SETOF ANYELEMENT AS
    $$
        SELECT ($1)[s] FROM generate_series(1,array_upper($1, 1)) AS s;
    $$
    LANGUAGE SQL IMMUTABLE;
    

    Then, you could pass a delimited string to your stored procedure.

    Say, param1 was an input param containing '1|2|3|4|5'

    The statement:

    SELECT CAST(fnExplode(string_to_array(param1, '|')) AS INTEGER);
    

    results in a result set that can be joined or inserted.

    Likewise, for MySQL, you could do something like this:

    DELIMITER $$
    CREATE PROCEDURE `spTest_Array`
    (
        v_id_arr TEXT
    )
    BEGIN
        DECLARE v_cur_position INT; 
        DECLARE v_remainder TEXT; 
        DECLARE v_cur_string VARCHAR(255); 
        CREATE TEMPORARY TABLE tmp_test
        ( 
            id INT
        ) ENGINE=MEMORY; 
    
        SET v_remainder = v_id_arr; 
        SET v_cur_position = 1;
    
        WHILE CHAR_LENGTH(v_remainder) > 0 AND v_cur_position > 0 DO 
            SET v_cur_position = INSTR(v_remainder, '|'); 
            IF v_cur_position = 0 THEN 
                SET v_cur_string = v_remainder; 
            ELSE 
                SET v_cur_string = LEFT(v_remainder, v_cur_position - 1); 
            END IF; 
    
            IF TRIM(v_cur_string) != '' THEN 
                INSERT INTO tmp_test
                    (id)
                VALUES 
                    (v_cur_string);                 
            END IF; 
    
            SET v_remainder = SUBSTRING(v_remainder, v_cur_position + 1); 
        END WHILE; 
    
        SELECT 
            id
        FROM 
        tmp_test;
    
        DROP TEMPORARY TABLE tmp_test;
    END 
    $$
    

    Then simply CALL spTest_Array('1|2|3|4|5') should produce the same result set as the above PostgreSQL query.

    0 讨论(0)
提交回复
热议问题