postgresql - 在函数中使用 plpgsql 复制到 csv 的动态 csv 文件导出错误

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

我正在尝试过滤 postgresql 表以查找将产品 ID 作为外键的行。对于每个产品 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;

最佳答案

试试这个

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;

修改:

create or replace function exportdata_1() returns void as 
$$
declare
rec record;
begin
for rec in
select format('copy(select * from trndailyprices where products=''%s'') to ''%s'' with csv',product,'D:/testQ/'||product||'.csv;') scr from(
Select distinct products from trndailyprices )t
loop
execute rec.scr;
end loop;
end;
$$
language plpgsql

关于postgresql - 在函数中使用 plpgsql 复制到 csv 的动态 csv 文件导出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29890149/

相关文章:

java - 将整数列表添加到 csv 文件中(JAVA)

python - 如何将这段数据保存到csv文件中?

powershell - 新对象不能包含破折号(-),但可以包含 “needs to”

sql - 用于分隔查询文件中多个查询的 PostgreSQL 定界符

sql - 在带有 UNION 子句的 postgres 中使用 ORDER BY 的问题

django - 使用固定装置将 django admin auth.groups 和用户迁移到新数据库

sql - PostgreSQL 动态表访问

postgresql - 用于可变列数查询的 Postgres CrossTab

sql - 从函数返回查询?

sql - PL/pgSQL : Add static column to query result