Hey everyone, I’m stuck with a PostgreSQL error. My function to rank players by height isn’t working. The error says:
ERROR: missing "LOOP" at end of SQL expression
CONTEXT: compilation of PL/pgSQL function "player_height_rank" near line 9
Here’s a simplified version of my code:
CREATE FUNCTION athlete_size_position(name_first TEXT, name_last TEXT) RETURNS INTEGER AS $$
DECLARE
position INTEGER := 0;
gap INTEGER := 0;
last_size INTEGER := NULL;
athlete RECORD;
BEGIN
FOR athlete IN SELECT
((a.height_m * 100) + (a.height_cm)) AS total_height,
a.name_first,
a.name_last
FROM athletes a
WHERE a.name_first = $1 AND a.name_last = $2
ORDER BY total_height DESC, a.name_first, a.name_last
-- LOOP keyword missing here?
IF athlete.total_height = last_size THEN
gap := gap + 1;
ELSE
position := position + gap + 1;
gap := 0;
last_size := athlete.total_height;
END IF;
IF athlete.name_last = $2 AND athlete.name_first = $1 THEN
RETURN position;
END IF;
END LOOP;
RETURN -1;
END;
$$ LANGUAGE plpgsql;
Can someone help me spot where the ‘LOOP’ keyword should go? Thanks!