X-Original-To: pgsql-sql-postgresql.org@localhost.postgresql.org Received: from localhost (unknown [200.46.204.144]) by svr1.postgresql.org (Postfix) with ESMTP id ACDD73AC3BE for ; Wed, 15 Dec 2004 18:54:53 +0000 (GMT) Received: from svr1.postgresql.org ([200.46.204.71]) by localhost (av.hub.org [200.46.204.144]) (amavisd-new, port 10024) with ESMTP id 69967-09 for ; Wed, 15 Dec 2004 18:54:48 +0000 (GMT) Received: from www.bowmansystems.com (ns1.bowmansystems.com [65.166.193.2]) by svr1.postgresql.org (Postfix) with ESMTP id CA2F63B4A8D for ; Wed, 15 Dec 2004 18:54:44 +0000 (GMT) Received: from ads2.ucomics.com (unknown [65.166.193.11]) by www.bowmansystems.com (Postfix) with ESMTP id 3C0D8C4F5 for ; Wed, 15 Dec 2004 12:42:20 -0600 (CST) Subject: Breadth first traversal in PLSQL (How to implement Queue?) From: Richard Rowell To: PostgreSQL SQL Content-Type: text/plain Date: Wed, 15 Dec 2004 12:54:44 -0600 Message-Id: <1103136884.9908.22.camel@richard> Mime-Version: 1.0 X-Mailer: Evolution 2.0.2 Content-Transfer-Encoding: 7bit X-Virus-Scanned: by amavisd-new at hub.org X-Spam-Status: No, hits=2.007 tagged_above=0 required=5 tests=DNS_FROM_RFC_ABUSE, DNS_FROM_RFC_POST, FORGED_RCVD_HELO, UPPERCASE_25_50 X-Spam-Level: ** X-Archive-Number: 200412/96 X-Sequence-Number: 19716 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 --