0

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

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; 
              ^
+1

我认为你需要pgplsql这里'执行fromat()' –

回答

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 $$; 
+0

是啊,作品。我还将表格更改为%I,并将字段更改为%s。谢谢,@klin。 –