postgresql - How to write SQL query to get column wise comma separated value list from record -


i searching sql query(i using postgres database) can give values single record in comma separated.

e.g.

i have table named master_table , having column no,name,phone

select * form master_table id = 1 

from above query want result as

1,piyush,1111111 2,john,2222222 

above table example tables dynamic column numbers , names cannot fixed.

thanks in advance

select (column_no::text || ',' || name || ',' || phone::text) comma_separated master_table id = 1 

edit :

after comment, think you'd need function. if don't agree whole idea (it's better in application layer), here function makes asking. ugly.

create or replace function getcommaseparatedvalues(par_table text, par_where_clause text default '') returns table (      comma_separated_values text ) $$ declare     rec_columns record;     var_query text; begin     var_query := '';     rec_columns in select column_name information_schema.columns table_schema = current_schema , table_name = par_table loop         if var_query <> ''             var_query := var_query || ' || '','' || ';         end if;         var_query := var_query || ' case when ' || rec_columns.column_name || ' null ''null'' else ' || rec_columns.column_name || '::text end';     end loop;     var_query := 'select ' || var_query || ' ' || par_table::regclass || ' ' || par_where_clause;     return query execute var_query; end; $$ language plpgsql; 

usage:

select * getcommaseparatedvalues('table1'); 

or

select * getcommaseparatedvalues('table2', 'where id = 1'); 

Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -