【问题标题】:Error in writing function in PostgreSQL在 PostgreSQL 中编写函数时出错
【发布时间】:2017-07-04 08:32:56
【问题描述】:

我已经使用这个 sn-p 代码创建了一个函数,用于在 PostgreSQL 中以 JSON 格式导出表。但是当我想使用动态路径来存储我的输出 JSON 文件作为函数的输入参数时,就会出现问题。当我用 'c:\myfile.json' 之类的东西替换 'path' 变量时,它没有任何错误。路径变量有什么问题?谢谢。

CREATE OR REPLACE FUNCTION ST_Export2JSON(tableName TEXT, fields TEXT, path TEXT)
RETURNS VOID AS 
$$
Copy(SELECT row_to_json(fc)
FROM ( SELECT 'FeatureCollection' As type, array_to_json(array_agg(f)) As     features
FROM ( SELECT 'Feature' As type, ST_AsGeoJSON(hp.geom)::json As geometry, row_to_json((select l from(select fields) as l)) As properties 
FROM tableName As hp ) As f )  As fc) to path;
$$
LANGUAGE sql IMMUTABLE STRICT

这是错误:

ERROR:  syntax error at or near "path"
LINE 7:  FROM tableName As hp ) As f )  As fc) to path;
                                              ^

【问题讨论】:

  • 我认为你需要 pgplsql 和execute fromat()

标签: json postgresql stored-procedures user-defined-functions


【解决方案1】:

你应该使用plpgsql dynamic command,例如:

create or replace function example(path text)
returns void language plpgsql as $$
begin
    -- instead of
    -- copy (select 1) to path;
    -- use:
    execute format('copy (select 1) to %L', path);
end $$;

【讨论】:

  • 是的,它有效。我还将表格更改为 %I,将字段更改为 %s。谢谢,@klin。
猜你喜欢
  • 2012-12-13
  • 1970-01-01
  • 1970-01-01
  • 2022-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-18
相关资源
最近更新 更多