I'm trying to execute a query within a loop which is within another loop, which is within an anonymous code block.
I'm trying to run this query
query := 'CREATE VIEW hopsPartialDistance AS '
||'SELECT AvgDistance '
||'FROM Distance '
||'WHERE PlanetOrigin = ' || rHops.PlanetOrigin
||' AND PlanetDestination = ' || rHops.PlanetDestination;
EXECUTE query;
But I keep getting the error
relation "hopspartialdistance" already exists
I then run
\d hopspartialdistance;
And the output is
Did not find any relation named "hopspartialdistance".
So I don't know where the error is coming from.
Here's the full function
DO
$$
DECLARE
routeDistance real := 0.0;
hopDistance real := 0.0;
rRoute record;
rHops record;
query text := '';
BEGIN
FOR rRoute IN
SELECT MonitoringKey FROM TradingRoute
LOOP
query := 'CREATE VIEW PortsOfCall AS '
||'SELECT PlanetID, VisitOrder '
||'FROM EnrichedCallsAt '
||'WHERE MonitoringKey = ' || rRoute.MonitoringKey
||' ORDER BY VisitOrder';
EXECUTE query;
CREATE VIEW Hops AS
SELECT A.PlanetID AS PlanetOrigin,
B.PLanetID AS PlanetDestination
FROM PortsOfCall A INNER JOIN PortsOfCall B ON A.VisitOrder + 1 = B.VisitOrder;
routeDistance = 0.0;
FOR rHops IN
SELECT PlanetOrigin, PlanetDestination FROM Hops
LOOP
query := 'CREATE VIEW hopsPartialDistance AS '
||'SELECT AvgDistance '
||'FROM Distance '
||'WHERE PlanetOrigin = ' || rHops.PlanetOrigin
||' AND PlanetDestination = ' || rHops.PlanetDestination;
EXECUTE query;
hopDistance = (SELECT SUM(AvgDistance) FROM hopsPartialDistance) ;
routeDistance = routeDistance + hopDistance;
END LOOP;
INSERT INTO RouteLength (RouteMonitoringKey, RouteTotalDistance)
SELECT rRoute.MonitoringKey, routeDistance;
DROP VIEW Hops
CASCADE;
DROP VIEW PortsOfCall
CASCADE;
END LOOP;
END;
$$;