Following on from a this question, I have some dynamic SQL I'm running successfully in PL/PgSQL with EXECUTE
, but it doesn't seem to have the intended effect.
The following code is part of a plpgsql function that I have created. This intends to go to each point that is lying on the same track and for each point find its nearest point in order to eventually I will create a network between all the tracks. For some reson it is not working properly.
The i represent the number of the current track.
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