From: Randolf Richardson, DevNet SysOp 29 <rr@8x.ca>
To: pgsql-sql@postgresql.org
Subject: Re: SOLVED: Emulating 'connect by prior' using stored proc
Date: Mon, 17 Nov 2003 05:47:28 +0000 (UTC)
Message-ID: <Xns9435DB9CB5682rr8xca@200.46.204.72> (raw)
References: <B7AD8B4B4A337741B62E633B4827ADD9435D6C@svrexc02.aolau.ops.au.office.aol.com>
[sNip]
> In order to make this work with postgres an additional table is needed
> that can hold the level (depth) of the branch because pgsql doesn't like
> returning a tuple that isn't based on a defined structure. Once you've
> created this table you can pretty much forget about it.
>
> CREATE TABLE "node_relationships_n_level" (
> "level" integer
> ) inherits (node_relationships);
>
>
> Now create your stored procedure.
>
> CREATE OR REPLACE FUNCTION "crawl_tree" (integer,integer) RETURNS SETOF
> node_relationships_n_level AS 'DECLARE
> temp RECORD;
> child RECORD;
> BEGIN
> SELECT INTO temp *, $2 AS level FROM node_relationships WHERE
> child_node_id = $1;
>
> IF FOUND THEN
> RETURN NEXT temp;
> FOR child IN SELECT child_node_id FROM node_relationships WHERE
> parent_node_id = $1 ORDER BY ordinal LOOP
> FOR temp IN SELECT * FROM crawl_tree(child.child_node_id, $2 +
> 1) LOOP
> RETURN NEXT temp;
> END LOOP;
> END LOOP;
> END IF;
> RETURN NULL;
> END;
> ' LANGUAGE 'plpgsql';
>
>
> The second parameter must be zero. This is a kludge because this is a
> recursive function and I needed some way of passing the level to
> successive function calls. However, if you like, you could consider this
> to be a "level offset"--set it to '2' and all the levels returned will
> be n + 2.
>
> Execute "SELECT * FROM crawl_tree(682904,0)" and you're done.
>
> Hope this helps people.
I have one question because I'm not clear about something with your
implementation (a good one too by the looks of it -- thanks for sharing
this information); if I start my query from an item at level 5, will the
level be reflected as such, or will it dynamically start at 1?
As I understand it, in Oracle the level would begin at 1 in this case.
Thanks in advance.
--
Randolf Richardson - rr@8x.ca
Inter-Corporate Computer & Network Services, Inc.
Vancouver, British Columbia, Canada
http://www.8x.ca/
This message originated from within a secure, reliable,
high-performance network ... a Novell NetWare network.
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Reply to all the recipients using the --to and --cc options:
reply via email
To: pgsql-sql@postgresql.org
Cc: rr@8x.ca
Subject: Re: SOLVED: Emulating 'connect by prior' using stored proc
In-Reply-To: <Xns9435DB9CB5682rr8xca@200.46.204.72>
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox