Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Help With Stored Proc to retrieve Hierarchical Data 1

Status
Not open for further replies.

Kalisto

Programmer
Feb 18, 2003
997
GB
I have an existing Database with 2 tables represented as follows

Code:
table productCategories

pKey, Description, DisplayOrder, ... (other fields elided)

table productCategoryRelationships
parentKey, childKey

The aim of these tables is to allow a category to have sub categories on a 0 to many basis, and also allow cross linking of categories.

I want to retrieve the data such that I can get each category, with any child categories afterwards. The main issue I have is that the Display Order, as I want to group the records so that I get Parent, Child nodes in order, next parent and so on.

so if I have the data like

Code:
productCategories

1, category1, 1, ...
2, category2, 2, ...
3, category3, 3, ...
4, category4, 4, ...
5, category2_1, 1, ...
6, category2_2, 2, ...


productCategoryRelationships
2,5
2,6

I can get the data out like so;
1, category1, 1, ...
2, category2, 2, ...
5, category2_1, 1, ...
6, category2_2, 2, ...
3, category3, 3, ...
4, category4, 4, ...

The best I have so far is ;

Code:
select * from productCategories as c
left outer join productCategoryRelationships as r
on r.parentkey = c.pKey

left outer join productCategories as c2
on c2.pkey = r.childKey

order by c.order, c2.order

the only issue with this is that my code is picking up the order from all the records from c first, so I get

Code:
1, category1, 1, ...
5, category2_1, 1, ...
2, category2, 2, ...
6, category2_2, 2, ...
3, category3, 3, ...
4, category4, 4, ...

So how do I resolve this, or do I need to get the database redesigned?
 
Im using sql2008 and I cant get it right, I might just can this and do it in code on the front end, as much as I'd prefer to do it in Sql, and also to learn how it is done, I dont think my boss will give me th eluxury of time to learn this technique..
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top