Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
chrisg229
Starting Member
12 Posts |
Posted - 2008-01-04 : 22:42:19
|
| I need to create a table that supports a potentially infinite amount of subcategories. An example would be:Food Pastries(Parent=Food) Cupcakes(Parent=Pastries) Chocolate(Parent=Cupcakes) Vanilla(Parent=Cupcakes) Danish(Parent=Pastries) Meat(Parent=Food) Beef(Parent=Meat) Chicken(Parent=Meat) Cajun(Parent=Chicken) Fried(Parent=Chicken)The subcategories will vary in depth.Can someone demonstrate a table create statement and then the proper select to pull this type of data?Many thanks in advance. |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2008-01-06 : 04:48:02
|
| Table structure will be some thing likeCREATE TABLE CategoriesTable(CategoryID int IDENTITY(1,1) PRIMARY KEY,Category varchar(100),ParentCategoryID int DEFAULT 0 REFERENCES CategoriesTable (CategoryID))and you can make use of recursive CTE to retrieve data like:-With Category_CTE (Level,CategoryID,Category) AS(SELECT 0,CategoryID,Category--Root level record. this forms anchor memberFROM CategoriesTableWHERE ParentCategoryID=0UNION ALLSELECT Level+1,c.CategoryID,c.Category--Child records.this forms recursive memberFROM CategoriesTable cINNER JOIN Category_CTE ccteON ccte.CategoryID=c.ParentCategoryID)SELECT * FROM Category_CTE --gets you full hierarchy |
 |
|
|
chrisg229
Starting Member
12 Posts |
Posted - 2008-01-07 : 13:57:32
|
| Thanks visakh |
 |
|
|
|
|
|