Dynamic column in SELECT statement postgres

后端 未结 6 1654
温柔的废话
温柔的废话 2020-12-20 14:55

I am quite new to the postgresql.

what is the best way to achieve this?

SELECT get_columns() 
  FROM table_name;

get_columns(

6条回答
  •  青春惊慌失措
    2020-12-20 15:54

    You wont be able to use a function to generate a column list. And I really don't think this is the best way to approach the problem... That said, you can do it with 8.4 like so:

    CREATE OR REPLACE FUNCTION dyn(p_name VARCHAR)
    RETURNS SETOF RECORD AS
    $$
      DECLARE
        p_sql  TEXT;
      BEGIN
       SELECT 'SELECT ' ||
         CASE p_name WHEN 'foo' THEN ' col1, col2, col3, col4 '
          WHEN 'bar' THEN 'col3, col4, col5, col6'
          WHEN 'baz' THEN 'col1, col3, col4, col6' END ||
       ' FROM mytest'
       INTO p_sql;
       RETURN QUERY EXECUTE p_sql;
      END
    $$ LANGUAGE 'plpgsql';

    Usage would be: SELECT * FROM dyn('foo') AS (one int, two int, three int, four int)

    But honestly I'd suggest just making a view for each device.

提交回复
热议问题