PostgreSQL写函数出错
Error in writing function in PostgreSQL
我使用此代码片段创建了一个函数,用于在 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;
^
您应该使用 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 $$;
我使用此代码片段创建了一个函数,用于在 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;
^
您应该使用 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 $$;