问题
Like advised I am linking to my previous question:
PL/pgSQL control structures for lists / arrays
I want to pass a list of numbers and a list of characters into a Postgres stored procedure. After that I want to do something with those two arrays. For number list you already helped me. I used CREATE OR REPLACE FUNCTION my_proc(p_amount_list numeric[]) as input parameter, and when I called that procedure I used SELECT my_proc('{2,2,2}');.
Now I want to know how to pass a list of characters and also how to call the procedure after that.
回答1:
You could build a function that either concatenates strings or sums up numeric values depending on the polymorphic input type:
CREATE OR REPLACE FUNCTION poly_sum_agg(_arr anyarray)
RETURNS text AS
$func$
BEGIN
CASE (SELECT e.typcategory FROM pg_type e
WHERE e.oid = (SELECT typelem FROM pg_type WHERE oid = pg_typeof(_arr)))
WHEN 'S' THEN -- string types: char, name, text, bpchar, varchar
RETURN array_to_string(_arr, ''); -- no separator?
WHEN 'N' THEN -- numeric: int8, int2, int4, oid, float4, float8, money, numeric
RETURN (SELECT sum(elem)::text FROM unnest(_arr) elem);
ELSE
RAISE EXCEPTION 'Unexpected array type!';
END CASE;
END
$func$ LANGUAGE plpgsql;
Call (note the explicit type cast):
SELECT poly_sum_agg('{1,2,3}'::int[]) AS int_arr; -- Returns '6'
Or:
SELECT poly_sum_agg('{1,2,3}'::text[]) AS text_arr; -- Returns '123'
SQL Fiddle.
This is just a proof of concept. It builds on the internal representation of array types in the system catalog pg_type and may not be portable across major releases. Here is how I retrieved information fro the system catalog:
SQL Fiddle.
It's largely unclear what your exact objective is. Depending on what you actually need, I would most probably take a different approach.
来源:https://stackoverflow.com/questions/27823248/passing-an-array-to-stored-to-postgres