Sql 使用copy from命令在postgres中进行变量连接时出现问题

Sql 使用copy from命令在postgres中进行变量连接时出现问题,sql,postgresql,plpgsql,Sql,Postgresql,Plpgsql,我正在尝试将一些包含json数据的文本文件插入到数据库中。每个文件的后缀都是1,2,3。。。等(shapes_routes1.json、shapes_routes2.json等)。要做到这一点,我将从循环中连接一个索引到基本文件名。我得到这个错误: psql:insertshapes.sql:37: ERROR: syntax error at or near "file_path" LINE 17: copy temp_json from file_path; 您不能为copy from提

我正在尝试将一些包含json数据的文本文件插入到数据库中。每个文件的后缀都是1,2,3。。。等(shapes_routes1.json、shapes_routes2.json等)。要做到这一点,我将从循环中连接一个索引到基本文件名。我得到这个错误:

psql:insertshapes.sql:37: ERROR:  syntax error at or near "file_path"
LINE 17: copy temp_json from file_path;
您不能为
copy from
提供变量作为路径吗?或者我需要对变量(file_path)做些什么,以便psql知道它的路径? 如果您对此有任何帮助或建议,我们将不胜感激

 delete from shapes;

    DO $$

    declare
        n INTEGER := 1;
        prefix TEXT := '/Users/me/model/json/filechunks/shapes_routes';
        i TEXT := NULL;
        file_path TEXT := NULL;

    BEGIN
    LOOP 
    EXIT WHEN n = 166;
    i := CAST(n as TEXT);
    file_path := prefix || i || '.json';
    n := n + 1;

    create temporary table temp_json (values text);
    copy temp_json from file_path; --GETTING ERROR ON THIS LINE
    insert into shapes

    select  values->>'shape_id' as shape_id,
            (CAST(values->>'shape_pt_lat' as real)) as shape_pt_lat,
            (CAST(values->>'shape_pt_lon' as real)) as shape_pt_lon,
            (CAST(values->>'shape_pt_sequence' as integer)) as shape_pt_sequence,
            (CAST(values->>'shape_dist_traveled' as real)) as shape_dist_traveled,
            values->>'route_id' as route_id

    from   (
            select json_array_elements(replace(values,'\','\\')::json) as values 
            from   temp_json
           ) a;

    drop table temp_json;
    END LOOP; 
    END $$;

复制需要字符串文字,不能对文件名使用子选择

如果需要更改文件名,则需要使用动态sql, (
执行

例如:


如果文件是,如您所说,
shapes\u routes1.json
shapes\u routes2.json
。。。为什么要在名称上连接一个
/
?它将使名字成为
/Users/me/model/json/filechunks/shapes\u routes/1.json,而不是你提到的名字…我不知道:)漫长的一天。感谢此错误与预期相同。不相关,但是:如果在循环之前创建一次临时表,并在每次导入之前截断它,则效率会更高。在从etc放置执行副本后,我现在收到此错误。psql:insertshapes.sql:38:error:relation“file\u path”不存在第1行:从文件路径中选择复制临时json^查询:从文件路径上下文中选择复制临时json:PL/pgSQL函数内联代码块第18行在Executed处这意味着它找不到文件或看不到变量文件路径?execute看不到变量。感谢你的帮助!你是冠军。那真让我抓狂
EXECUTE 'copy temp_json from '||quote_literal(file_path);