Postgresql - return entire row as array

前端 未结 4 2197
南方客
南方客 2021-02-09 17:32

Is there a way how you can cast the following result to array?

select pg_tables from pg_tables

This will return one column only, however the da

4条回答
  •  感情败类
    2021-02-09 18:06

    This function works with all corner cases including NULL values, empty strings or special characters in the values.

    CREATE OR REPLACE FUNCTION f_rows_to_arr(_tbl text)
      RETURNS SETOF text[] AS
    $BODY$
    BEGIN
    
    RETURN QUERY EXECUTE '
    SELECT ARRAY[' || (
            SELECT string_agg(quote_ident(attname) || '::text', ',')
            FROM   pg_catalog.pg_attribute 
            WHERE  attrelid = _tbl::regclass  -- valid, visible table name 
            AND    attnum > 0                 -- exclude tableoid & friends
            AND    attisdropped = FALSE       -- exclude dropped columns
            ) || ' ]
    FROM   ' || _tbl::regclass;
    
    END;
    $BODY$ LANGUAGE plpgsql;
    

    Call:

    SELECT * FROM f_rows_to_arr ('mytbl');
    

    The cast to regclass avoids SQLi. Columns are not sorted in this version. More explanation for used techniques and links in this related answer.

提交回复
热议问题