从这个问题开始,我在 PL/PgSQL 中成功运行了一些动态 SQL EXECUTE
,但它似乎没有达到预期的效果。
以下代码是我创建的 plpgsql 函数的一部分。这打算去位于同一轨道上的每个点,并为每个点找到它最近的点,以便最终我将在所有轨道之间创建一个网络。对于某些共振,它无法正常工作。
i 代表当前曲目的编号。
DECLARE
_r record;
i int := 0;
source_geom character varying;
target_geom character varying;
BEGIN
WHILE i < 3 --DEPENDS ON THE NUMBER OF TRACKS
LOOP
FOR _r IN EXECUTE ' SELECT a.'|| quote_ident(gid_cname) || ' AS id,'
|| ' st_astext( a.'||quote_ident(geo_cname)||') AS source,'
|| ' st_astext(b.'||quote_ident(geo_cname)||') AS target, '
|| ' ST_Distance(a.'||quote_ident(geo_cname) || ' , b.'||quote_ident(geo_cname)||') As dist_ft'
|| ' FROM ' || quote_ident (geom_table) ||' AS a INNER JOIN ' || quote_ident(geom_table) || ' As b ON ST_DWithin(a.'||quote_ident(geo_cname)|| ', b.'||quote_ident(geo_cname)|| ',1000)'
|| ' WHERE b.'||quote_ident(gid_cname)|| ' > a.'||quote_ident(gid_cname)|| ' AND b.'||quote_ident(tid_cname)|| ' = '||i|| 'AND a.'||quote_ident(tid_cname)|| ' = '||i||
' ORDER BY dist_ft '
|| ' Limit 1 '
LOOP
source_geom := _r.source;
target_geom := _r.target;
EXECUTE 'update ' || quote_ident(geom_table) ||
' SET source = ''' || source_geom ||'''
, target = ''' || target_geom || '''
WHERE ' || quote_ident(gid_cname) || ' = ' || _r.id;
END LOOP;
i = i + 1;
END LOOP;
RETURN 'OK';
END;
The thing is that I have tested the query in plain sql and it worked brilliantly. Now for some reason in plpgsql it is not working properly. Below you can find the same query in plain sql.
SELECT a.ogc_fid AS id, st_astext( a.wkb_geometry) AS source, st_astext(b.wkb_geometry) AS target, ST_Distance(a.wkb_geometry, b.wkb_geometry) As dist_ft
FROM track_points AS a INNER JOIN track_points As b
ON ST_DWithin(a.wkb_geometry , b.wkb_geometry, 1000)
WHERE b.ogc_fid > a.ogc_fid AND b.track_fid = 0 AND a.track_fid = 0
order by dist_ft