使用来自命令的复制在postgres中进行变量串联的问题

时间:2018-07-05 05:34:42

标签: 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提供变量作为路径吗?还是我需要对变量(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 $$;

1 个答案:

答案 0 :(得分:1)

COPY需要字符串文字,您不能使用子选择作为文件名。

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

例如:

EXECUTE 'copy temp_json from '||quote_literal(file_path);
相关问题