Question

Several of the introductory tutorials I've read on using for loops in plpgsql have said unless I really need a for loop, I should find another way.

As a programming novice I can't figure out a better way than a for loop.

I would like to go through each parcel gid, calculate the nearest street intersection by bounding box, then assign the intersection id to the nearest_intersection column in parcels.

All the parts of this function work nicely. But I can't figure out how to put them together.

BEGIN

FOR gid IN SELECT gid FROM parcels 
LOOP
UPDATE parcels SET nearest_intersection = 
    (select intersection.osm_id
     from intersections
     order by
     intersections.geom <-> (select geom from parcels where gid = parcel_id)
     limit 1;)
end loop;
end;

Thank you!

Était-ce utile?

La solution

In your current code, the loop doesn't make sense indeed because the UPDATE alone already processes every row of the parcels table.

What you probably want is (without a loop):

UPDATE parcels R SET nearest_intersection = 
    (select intersection.osm_id
     from intersections
     order by intersections.geom <-> R.geom
     limit 1);

which in procedural thinking would be the equivalent to:

for every row R of parcels, find the row in intersections whose geom is the nearest to R.geom and copies its osm_id into R.nearest_intersection


On the other hand, if it had to be done with a loop, it would look like this:

FOR var_gid IN SELECT gid FROM parcels 
LOOP
UPDATE parcels SET nearest_intersection = 
    (select intersection.osm_id
     from intersections
     order by
     intersections.geom <-> parcels.geom)
     limit 1)
  WHERE parcels.gid=var_gid;
end loop;

Autres conseils

Don't be a hostage of SQL purism. Write functions with loops. When you are a postgres expert you'll change them to queries. Or not.

You probably missed WHERE clause for UPDATE.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top