Yancho
By: a guest | Dec 6th, 2007 | Syntax:
SQL | Size: 1.96 KB | Hits: 88 | Expires: Never
CREATE OR REPLACE FUNCTION near_hospital(text, integer, integer)
RETURNS integer AS
$BODY$
DECLARE
pojnt ALIAS FOR $1;
box ALIAS FOR $2;
dist ALIAS FOR $3;
distances RECORD;
nearest RECORD;
BEGIN
nearest.dist := 1000000000;
FOR distances IN
SELECT astext(h.the_geom) AS hospital_location FROM hospitals h WHERE
(
h.the_geom && expand (pointfromtext(pojnt),100000) AND
distance ( h.the_geom , pointfromtext(pojnt) ) < 150000
)
ORDER BY distance (h.the_geom , pointfromtext(pojnt)) ASC
LIMIT 3;
LOOP
SELECT INTO hospital gid, the_geom, length(the_geom) AS dist FROM shootingstar_sp
( 'streets',
(
SELECT s.gid FROM streets s, hospitals h WHERE
source = (
SELECT give_source(distances.hospital_location,100000,150000))
LIMIT 1
)
,
(
SELECT gid FROM streets WHERE
target = (SELECT give_target(pojnt,100000,150000))
LIMIT 1
)
,
5000,
'length',
true,
true
);
IF hospital.dist < nearest.dist THEN
nearest.dist := hospital.dist;
nearest.gid := hospital.gid;
SELECT INTO nearest name FROM hospital h
WHERE h.gid = hospital.gid ;
END IF;
END LOOP;
RETURN nearest.gid;
END;
' language 'plpgsql';