在函数中使用plpgsql复制到csv导出动态csv文件时出错

时间:2015-04-27 07:56:30

标签: postgresql plpgsql export-to-csv postgresql-copy

我正在尝试为具有产品ID作为外键的行过滤postgresql表。对于每个产品ID,我需要将1个csv各自导出到一个文件夹,例如prod1.csv,prod2.csv等。我尝试创建下面的函数来自动执行此操作但是当我运行它时函数失败。任何人都可以帮助我修复功能或推荐更好的方法吗?

CREATE or replace FUNCTION exportdata() 
RETURNS SETOF record AS
$$
DECLARE
 rec text;
BEGIN
 FOR rec IN 
(
Select distinct t.products from trndailyprices as t --Get the list of products in the table
) 
 LOOP
    Copy (
    Select * from trndailyprices as t
    where t.products = rec   ---1st record is product1
    order by t.effectivedate) 
    To 'C:/testQ/' ||rec || '.csv' With CSV;---expected file is product1.csv for 1st record
 END LOOP;
END;
$$ LANGUAGE plpgsql;

1 个答案:

答案 0 :(得分:3)

试试这个

Arrays.sort()

修改:

CREATE or replace FUNCTION exportdata() 
RETURNS void AS -- use void because you're not returning anything 
$$
DECLARE
 rec text;
BEGIN
 FOR rec IN 
Select distinct t.products from trndailyprices as t 
 LOOP
EXECUTE -- you need to use EXECUTE Keyword 
    format('Copy (
    Select * from trndailyprices as t
    where t.products =''%s''
    order by t.effectivedate) 
    To ''C:/testQ/%s.csv'' With CSV;',rec,rec);
 END LOOP;
END;
$$ LANGUAGE plpgsql;