Re: SOLVED: Emulating 'connect by prior' using stored proc - Mailing list pgsql-sql

From Randolf Richardson, DevNet SysOp 29
Subject Re: SOLVED: Emulating 'connect by prior' using stored proc
Date
Msg-id Xns9435DB9CB5682rr8xca@200.46.204.72
Whole thread Raw
In response to SOLVED: Emulating 'connect by prior' using stored proc  ("Merrall, Graeme" <gmerrall@team.aol7.com.au>)
List pgsql-sql
[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.



pgsql-sql by date:

Previous
From: "Randolf Richardson, DevNet SysOp 29"
Date:
Subject: Re: HELP ME
Next
From: "Randolf Richardson, DevNet SysOp 29"
Date:
Subject: Re: Oracle 'connect by prior' now eaiser in 7.3?