tags:

views:

365

answers:

4

I am quite new to the postgresql.

what is the best way to achieve this?

SELECT get_columns() 
  FROM table_name;

get_columns() will provide the column names for the query. I saw people advising to use EXECUTE statement but I couldn't got that working.

Lets say there is table Test with columns a,b,c and I want to run

SELECT a,b FROM Test;
SELECT a,c FROM Test;

with column names generated dynamically.

A: 

This is how you get the columnnames in a table:

SELECT 
  column_name 
FROM 
  information_schema.columns 
WHERE 
  table_name = 'test';
Frank Heikens
yeah I know this. The question is can we construct a SELECT statement dynamically?
Sujit
A: 

In such case I would use PL/pgSQL function using cursor.

Michał Niklas
A: 

Since you are using COPY FROM to a known large table, CREATE a FUNCTION which returns SETOF bigtable and SELECTs all the columns from the specific type, use NULL AS fieldname for the fields which are not required in that specific case, something like:

# \d SMALL
     Table "public.small"
 Column |  Type   | Modifiers 
--------+---------+-----------
 a      | integer | 
 b      | integer | 
 c      | integer | 
 d      | integer | 

# \d LARGE
     Table "public.large"
 Column |  Type   | Modifiers 
--------+---------+-----------
 a      | integer | 
 b      | integer | 
 c      | integer | 
 d      | integer | 

# CREATE OR REPLACE FUNCTION myData()
 RETURNS SETOF large LANGUAGE SQL AS $$
SELECT a, 
       CASE WHEN a = 1 
            THEN b 
       ELSE 
            NULL 
END as b, 
       CASE WHEN a = 2 
            THEN c 
       ELSE 
            NULL
END AS c, 
d
FROM small;
$$;

# SELECT * FROM mydata();
# COPY (SELECT * FROM myData()) TO STDOUT;

Obviously SQL might not be the best language to use, so PL/PgSQL or PL/Perl (or whatever) may be appropriate.

MkV
this seems to be the wrong way round, feel free to ignore this answer
MkV
A: 

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.

Scott Bailey