Search code examples
stored-proceduresparametersamazon-redshift

Is it possible to pass in a variable amount of parameters to a stored procedure in redshift?


I am trying to write a stored procedure in AWS Redshift SQL and one of my parameters needs the possibility to have an integer list (will be using 'IN(0,100,200,...)' inside there WHERE clause). How would I write the input parameter in the header of the procedure so that this is possible (if at all?)

I've tried passing them in as a VARCHAR "integer list" type thing but wasn't sure then how to parse that back into ints.

Update: I found a way to parse the string and loop through it using the SPLIT_PART function and store all of those into a table. Then just use a SELECT * FROM table with the IN() call


Solution

  • What I ended up doing was as follows. I took in the integers that I was expecting as a comma-separated string. I then ran the following on it.

    CREATE OR REPLACE PROCEDURE test_string_to_int(VARCHAR)
    AS $$
    DECLARE
        split_me ALIAS FOR $1;
        loop_var INT;
    BEGIN
        DROP TABLE IF EXISTS int_list;
    
        CREATE TEMPORARY TABLE int_list (
                integer_to_store INT
        );
    
        FOR loop_var IN 1..(REGEXP_COUNT(split_me,',') + 1) LOOP
                INSERT INTO int_list VALUES (CAST(SPLIT_PART(split_me,',',loop_var) AS INT));
        END LOOP;
    
    END;
    $$ LANGUAGE plpgsql;
    

    So I would call the procedure with something like:

    CALL test_string_to_int('1,2,3');
    

    and could do a select statement on it to see all the values stored into the table. Then in my queries the need this parameter I ran:

    .........................
    WHERE num_items IN(SELECT integer_to_store FROM int_list);