将数据从 postgres 保存到文件 txt 或 csv

时间:2021-02-11 17:52:04

标签: postgresql psql pgadmin

请告诉我执行更新语句时是否可以保存任何数据文件?

我在 postgres pgadmin / psql 中执行这个函数

do
$$
declare 
    nr int;
    status varchar(100);
begin
    select count(*) into nr from film where title = 'Academy Dinosaur';
    if nr = 1 then
        update film
        set length = 1000
        where title = 'Academy Dinosaur';
        status := 'Success';
        end if;
end;$$

我想写入文件(如果更新成功执行)是这样的: 标题 = 标题,状态 = 成功(如果成功)但我不知道如何执行此操作以及如何将状态值返回到文件?我不想复制所有表。

1 个答案:

答案 0 :(得分:1)

do language plpgsql
$$
brgin
 update film
    set length = 1000
  where title = 'Academy Dinosaur';
 if FOUND then
   copy (select format('Title = %s, Status = %s', 'Academy Dinosaur', 'Success')) 
     to 'path-to-your-file';
 enf if;
end;
$$;

format 和文本替换仅适用于您想要使用变量的情况。否则就(select 'Title = Academy Dinosaur, Status = Success')