Breadth first traversal in PLSQL (How to implement Queue?)

From: Richard Rowell <richard(at)bowmansystems(dot)com>
To: PostgreSQL SQL <pgsql-sql(at)postgresql(dot)org>
Subject: Breadth first traversal in PLSQL (How to implement Queue?)
Date: 2004-12-15 18:54:44
Message-ID: 1103136884.9908.22.camel@richard
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

I have a table with a unary (recursive) relationship that represents a
hierarchy. With the gracious help of Mike Rylander I was able to port a
TSQL function that would traverse "up" the hierarchy to PL/SQL. Now I
need help porting the "down" the hierarchy function.

As implemented in TSQL I utilized a simple breadth first tree traversal.
I'm not sure how to replicate this in PL/SQL as I haven't figured out
how to implement the queue required for the breadth first algorithm. My
queue is declared "queue SETOF INTEGER" and I'm able to "SELECT INTO"
this variable. However when I try to delete the "current" value, I get
a syntax error. If I comment the delete out, I also get an error when I
try to fetch the "next" value from the front of the queue.

Below is the function, followed by the psql output:

CREATE OR REPLACE FUNCTION svp_getchildproviderids (INTEGER)
RETURNS SETOF INTEGER
AS '
DECLARE
parent_provider ALIAS FOR $1;
cid INTEGER;
queue SETOF INTEGER;
BEGIN
SELECT INTO cid count(*) FROM providers WHERE uid =parent_provider;
IF cid = 0 THEN
RAISE EXCEPTION ''Inexistent ID --> %'', parent_provider;
RETURN;
END IF;
cid := parent_provider;
LOOP
EXIT WHEN cid IS NULL;
RETURN NEXT cid;
SELECT INTO queue uid FROM providers WHERE parent_id = cid;
DELETE FROM queue WHERE queue.queue = cid;
SELECT INTO cid * FROM queue LIMIT 1;
END LOOP;
RETURN;
END;' LANGUAGE 'plpgsql';

sp_demo_505=# select * from svp_getchildproviderids(1);
ERROR: syntax error at or near "$1" at character 14
CONTEXT: PL/pgSQL function "svp_getchildproviderids" line 16 at SQL
statement

--

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Mike Rylander 2004-12-16 02:48:57 Re: Breadth first traversal in PLSQL (How to implement Queue?)
Previous Message Richard Huxton 2004-12-15 16:17:51 Re: [SQL] [Fwd: Majordomo results: unsubscribe]