【发布时间】:2021-06-18 14:53:39
【问题描述】:
我正在尝试编写一个 PL/PGSQL 函数,该函数将分隔文本作为输入并将行插入到包含点的表中。我有一个可以正常工作的测试功能:
rowsaz := string_to_array(input,'?');
INSERT INTO test (num1, num2, my_name)
SELECT * FROM unnest(string_to_array(rowsaz[1],',')::integer[],string_to_array(rowsaz[2],',')::integer[],string_to_array(rowsaz[3],',')::varchar[]);
return true;
所以如果你调用函数
SELECT myfunction('1,2,3?4,5,6?a,b,c')
然后你会得到一个类似的表
1 4 a
2 5 b
3 6 c
但是当你有一张这样的桌子时你怎么做
CREATE TABLE public.gps_points
(
id integer NOT NULL DEFAULT nextval('gps_id_seq'::regclass),
location geometry(Point,4326),
created_at timestamp with time zone DEFAULT CURRENT_TIMESTAMP,
user_id integer
)
插入看起来像 INSERT INTO gps_points (location, user_id) VALUES (ST_GeomFromText('POINT(-71.060316 48.432044)', 4326),2);
但这对于 unnest 会变得很棘手,因为您必须将坐标传递给 ST_POINT 函数。然后我会调用这个函数: SELECT myfunction('36.98,36.99,36.97?45.85,45.86,45.87?1,2,3')
我正在尝试执行以下操作,但它不起作用
insert into gps_points( geom, user_id)
select unnest( (ST_GeomFromText('POINT(string_to_array(rowsaz[1],',')::double precision[] string_to_array(rowsaz[2],',')::double precision[])', 4326),string_to_array(rowsaz[3],',')::double precision[]));
【问题讨论】:
标签: postgresql postgis plpgsql unnest