问题
I have two tables src_pos and dest_pos.
The src_pos stores positions with longitude, latitude and altitude, while the dest_pos stores PosGIS Geometry object.
Now I want to move a bunch of data from src_pos to dest_pos with following plpgsql script. But it failed, because row vaiable (e.g. row_data.longitude) cannot be interpreted correctly. How can I overcome this problem!?
--create language 'plpgsql';
drop function createPosition();
create function createPosition() returns integer AS
$$
DECLARE
updated INTEGER = 0;
row_data src_pos%ROWTYPE;
BEGIN
FOR row_data IN SELECT * FROM src_pos
LOOP
INSERT INTO dest_pos (coord) VALUES (ST_GeomFromText('POINT(row_data.longitude row_data.latitude row_data.altitude)', 4326));
updated := updated + 1;
END LOOP;
RETURN updated;
END;
$$
LANGUAGE 'plpgsql';
回答1:
Better yet, use ST_MakePoint to directly make a geometry object. This is not only faster than ST_GeomFromText, but it is lossless, since you don't need to convert numbers to text to numbers.
...
WITH result AS (
INSERT INTO dest_pos (coord)
SELECT ST_SetSRID(ST_MakePoint(longitude, latitude, altitude), 4326)
FROM src_pos
RETURNING 1
)
SELECT count(*) INTO updated FROM result;
RETURN updated;
...
回答2:
In the comment you gave your own solution:
ST_GeomFromText('POINT(' || row_data.longitude || ' ' || row_data.latitude ||
' ' || row_data.altitude || ')', 4326)
This is a perfectly good solution. I actually do something relatively similar in some cases in other areas of postgresql.
The fact is that every PostgreSQL type can be represented as text. If you are willing to manipulate these, you can transfer between types in ways that the normal type casting system does not allow.
来源:https://stackoverflow.com/questions/8433513/insert-postgis-object-e-g-st-geomfromtext-from-row-variables-in-plpgsql-scrip