I have the following function that takes a table name as parameter and returns the table:
CREATE FUNCTION func(tab_name varchar) RETURNS TABLE (
col text,
col2 text
) AS $$
BEGIN
RETURN QUERY
EXECUTE format('SELECT * FROM %I', tab_name);
END;
$$
LANGUAGE plpgsql;
Suppose instead, I wanted to do return the table 100 times:
CREATE FUNCTION func(tab_name varchar) RETURNS TABLE (
col text,
col2 text
) AS $$
BEGIN
RETURN QUERY
EXECUTE format('
SELECT * FROM %I
UNION ALL
SELECT * FROM %I,
UNION ALL
SELECT * FROM %I
......
', tab_name, tab_name, tab_name,.....);
END;
$$
LANGUAGE plpgsql;
Instead of putting tab_name 100 times is there some way to use named parameters?
You can indicate the position of an argument and use an argument multiple times, e.g.
select format('%2$s - %1$s - %2$s', 'first', 'second');
format
-------------------------
second - first - second
(1 row)
Read more in the documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With