Assuming fields
is supposed to be a column name.
CREATE OR REPLACE FUNCTION exa(ids text, length integer, fields text
,OUT result text) AS
$BODY$
DECLARE
_chars INT[] := string_to_array(ids, ',');
i integer := 0;
_temp text := '';
_arr text[];
BEGIN
FOR i IN 1..length loop
EXECUTE 'SELECT ' || fields || ' FROM user_index WHERE userid = chars[i]'
INTO temp;
_arr := _arr || temp;
END LOOP;
result := array_to_string(result, ',');
RETURN;
END
$BODY$ language plpgsql;
But really just:
CREATE OR REPLACE FUNCTION exa(ids text, fields text, OUT result text) AS
$BODY$
BEGIN
EXECUTE
format($$SELECT string_agg(%I, ',')
FROM user_index
JOIN unnest(string_to_array($1, ',')::int[]) i(userid)
USING (userid)$$
,fields)
USING ids
INTO result;
END
$BODY$ language plpgsql;
Call:
SELECT exa('10,11,12', 'kat')
And be sure to avoid SQL injection using format()
with %I
or some other sane method. Try the search tools. Many similar answers here on SO - like this one (with more explanation and links):
INSERT with dynamic table name in trigger function