|
vk59
Starting Member
38 Posts |
Posted - 2005-09-15 : 06:23:57
|
| we have a table to define Categories and Sub categories as below,CategoryId-->CategoryName-->ParentCategory1-->Beverages -->NULL2-->Food -->NULL3-->Cool Drinks -->14-->Hard Drinks -->15-->Poultry -->26-->Sea Food -->27-->Chicken -->58-->Mutton -->59-->Prawn -->610-->Fish -->6 We need a query wherein when an ID of sub category is passed, it should return all the parent Category Ids in the hierarchy.For E.g when Category id 10 is passed, query should return categories with IDs 10,6 and 2Thanks in advanceVK59` |
|
|
rythm123us
Starting Member
27 Posts |
Posted - 2005-09-17 : 10:00:56
|
| Here is something I use:DECLARE @Category TABLE(CategoryID INT, ParentID INT, CategoryText VARCHAR(55), Lineage VARCHAR(55), SortOrder INT)INSERT @Category(CategoryID, ParentID, CategoryText, Lineage, SortOrder) SELECT 1, 0, 'All', '1', 0 UNION ALL SELECT 2, 1, 'Beer', '1.1', 1 UNION ALL SELECT 3, 2, 'Domestic', '1.1.1', 2 UNION ALL SELECT 37, 1, 'Wine', '1.4', 38 UNION ALL SELECT 38, 37, 'Domestic', '1.4.1', 39 UNION ALL SELECT 39, 38, 'California', '1.4.1.1', 40-- Get all the ChildrenSELECT C1.*FROM @Category C1 INNER JOIN @Category C2 ON C2.Lineage = SUBSTRING(C1.Lineage, 1, LEN(C2.Lineage))WHERE C2.CategoryID = 37-- Get all the Parents SELECT C1.*FROM @Category C1 INNER JOIN @Category C2 ON C1.Lineage = SUBSTRING(C2.Lineage, 1, LEN(C1.Lineage))WHERE C2.CategoryID = 37The necessary Field here is Lineage |
 |
|