【发布时间】:2016-06-28 21:53:32
【问题描述】:
我正在尝试编写一些 SQL 来根据 information_schema 中的内容从给定数据库中的所有 PostgreSQL 表中复制数据。它应该将数据文件输出到我的本地机器,准备好导入另一台机器。最终,我将对此进行调整,以便仅转储表的选定部分(我要转储的一些表有数百万条记录,我只需要一小部分数据用于测试目的)。
这是我目前所拥有的......
--Copy all tables...
DO
$$
DECLARE
formatstring text;
rec record;
BEGIN
RAISE NOTICE 'Copying tables...';
formatstring = 'COPY (select * from %I) to ''C:\Media\Code\%s.csv'';';
FOR rec IN
select table_name from information_schema.tables where table_schema = 'public' order by table_name
LOOP
RAISE NOTICE 'Table: %', rec.table_name;
RAISE NOTICE format(formatstring, rec.table_name, rec.table_name);
EXECUTE format(formatstring, rec.table_name, rec.table_name);
END LOOP;
END;
$$
LANGUAGE plpgsql;
但是,我遇到了这个异常...
ERROR: unrecognized exception condition "format" CONTEXT: compilation of PL/pgSQL function "inline_code_block" near line 12 ********** Error ********** ERROR: unrecognized exception condition "format" SQL state: 42704 Context: compilation of PL/pgSQL function "inline_code_block" near line 12
单引号的转义似乎很好(已经检查过这个问题:Insert text with single quotes in PostgreSQL)。事实上,我可以执行以下操作,并且可以将文本插入到格式中:
select format('COPY (select * from %I) to ''C:\Media\Code\%s.csv'';', 'system_user', 'system_user');
谁能帮助解决这个问题?我可以很容易地编写一个脚本或代码来为我生成复制命令,但是用一点简单的 SQL 来完成这一切会很棒。
【问题讨论】:
-
看到一个应有的问题是难得而愉快的:所有基本信息和最低限度的噪音,清晰呈现。起首!
标签: postgresql plpgsql postgresql-9.4 string-interpolation