Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL - Format() Named parameters?

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?

like image 614
Legend123 Avatar asked May 17 '26 14:05

Legend123


1 Answers

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.

like image 70
klin Avatar answered May 19 '26 04:05

klin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!