Click here to Skip to main content
15,886,137 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have to handle a table PRODUCTS which is created to accommodate tree structure of products. It is done to handle situations when one product can contain several others (e.g. one package product holds several other positions). So, I'm making a function that takes OrderDetails, and it must iterate through all PRODUCTS and list out the child products for each product listed. I am facing an issue that I have to iterate through tree of unknown depth. Please, give me an idea how to do it.

UPD. Tried to implement such structure in PostgreSQL, here is the code:
SQL
CREATE TABLE public.tree_products (
  product_id INTEGER DEFAULT nextval('ree_products_product_id_seq'::regclass) NOT NULL,
  name VARCHAR,
  parent_id INTEGER,
  CONSTRAINT ree_products_pkey PRIMARY KEY(product_id)
) 

CREATE OR REPLACE FUNCTION foo()RETURNS text AS
$body$
DECLARE _row RECORD;
		_result text := '';
        _child_row RECORD;
        _count integer := -1;
        _marker integer := 1;
BEGIN
	FOR _row IN SELECT * FROM tree_products
    LOOP
    	_result := _result || _marker || ' ' || _row.name;
    	_count := (SELECT count(product_id) FROM tree_products WHERE parent_id = _row.product_id);
        IF _count > 0 THEN
        	FOR _child_row IN SELECT * FROM tree_products WHERE parent_id = _row.product_id
            LOOP
            	_result := _result || ' ' || _child_row.name;
            END LOOP;
        END IF;
        _marker := _marker =1;   	
   	END LOOP;
END;
$body$
LANGUAGE plpgsql


That function goes throuh products table, but the depth of childs search is limited to 1. I want to have unlimited depth of listing.
Posted
Updated 28-Feb-14 1:42am
v4
Comments
Maciej Los 28-Feb-14 2:36am    
Please, specify tag: PostgreSQL or SQL for MS SQL Server.
v.chjen 28-Feb-14 3:07am    
Done
Maciej Los 28-Feb-14 3:21am    
OK, have you seen my answer?

1 solution

 
Share this answer
 
Comments
v.chjen 28-Feb-14 6:04am    
voted 5
Maciej Los 28-Feb-14 6:18am    
Thank you ;)
If my answer was helpful, please mark it as a solution (green button) - formally - to remove question from unanswered list ;)
v.chjen 28-Feb-14 7:11am    
updated question, because still there are some unclear parts form me
Maciej Los 28-Feb-14 7:19am    
Sorry, i'm not familiar with PostgreeSQL as wish to be.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900