vendredi 27 février 2015

Write output from dynamic queries in PL/pgSQL to CSV file



PG_CMD="psql -d portal -U portal -c "
PG_CMD_TP="psql -d portal -U portal -t -P format=unaligned -c "
abc()
{
$PG_CMD "
DO \$$
DECLARE
srowdata record;
customer_list varchar[];
customer_schema varchar(100);
portal_row a.portal%ROWTYPE;
var1 varchar(100);
temp varchar(100);
BEGIN
customer_list=ARRAY(select cname from customer);

FOREACH customer_schema IN ARRAY customer_list LOOP

EXECUTE format('select %s.portal.*,%s.p_fb_config.*,%s.p_gplus_config.*,%s.p_linkd_config.*,%s.p_localum_config.*,
%s.p_sms_config.*,%s.p_twt_config.*,%s.p_webform_config.*,%s.p_wechat_config.*,%s.p_clickthrough_config.*,%s.splash.*
from %s.portal left outer join %s.p_fb_config on %s.portal.pid = %s.p_fb_config.pid left outer join %s.p_gplus_config
on %s.portal.pid = %s.p_gplus_config.pid left outer join %s.p_linkd_config on %s.portal.pid = %s.p_linkd_config.pid left
outer join %s.p_localum_config on %s.portal.pid = %s.p_localum_config.pid left outer join %s.p_sms_config on
%s.portal.pid = %s.p_sms_config.pid left outer join %s.p_twt_config on %s.portal.pid = %s.p_twt_config.pid left outer join
%s.p_webform_config on %s.portal.pid = %s.p_webform_config.pid left outer join %s.p_wechat_config on
%s.portal.pid = %s.p_wechat_config.pid left outer join %s.p_clickthrough_config on
%s.portal.pid = %s.p_clickthrough_config.pid left outer join %s.splash on %s.portal.pid=%s.splash.pid;', customer_schema,
customer_schema,customer_schema,customer_schema,customer_schema,customer_schema,customer_schema,customer_schema,
customer_schema,customer_schema,customer_schema,customer_schema,customer_schema,customer_schema,customer_schema,
customer_schema,customer_schema,customer_schema,customer_schema,customer_schema,customer_schema,customer_schema,
customer_schema,customer_schema,customer_schema,customer_schema,customer_schema,customer_schema,customer_schema,
customer_schema,customer_schema,customer_schema,customer_schema,customer_schema,customer_schema,customer_schema,
customer_schema,customer_schema,customer_schema,customer_schema,customer_schema,customer_schema) INTO srowdata;

raise notice ' %: %', customer_schema,srowdata;
END LOOP;
END;
\$$";
}

abc


I have written anonymous block in plpgsql. Now, instead of using raise notice I want to write this output in CSV format. I tried COPY but it accepts argument as a query.





Aucun commentaire:

Enregistrer un commentaire