Click here to Skip to main content
15,893,161 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hi every one.
I have a Table, that have Parent in Same Table like this :

SQL
CREATE TABLE [dbo].[tSameCategoryProducts](
    [CategoryProductID] [int] IDENTITY(1011,3) Primary Key NOT NULL,
    [CategoryProductParentID] [int] NULL,
    [CategoryText] [nvarchar](100) NULL,

GO

ALTER TABLE [dbo].[tSameCategoryProducts]  WITH CHECK ADD FOREIGN KEY([CategoryProductParentID])
REFERENCES [dbo].[tSameCategoryProducts] ([CategoryProductID])

GO


Imagine i have a tree in this Table, for Example :

ID   ParentID   Text

1  --  null    --   Car
2  --  1       --   Sport
3  --  2       --   Lamborghini
.
.
.




Is there any way that in One Select have Something like This ? :


Text     ---      AllParents

Car      ---      Car
Sport    ---     Car/Sport
Lamborghini  ---   Car/Sport/Lamborghini
.
.
.


Thanks in Advance.
Posted
Updated 25-May-12 21:05pm
v2

1 solution

You can use Common Table Expression[^] to create cumulate values from previous rows.

For example something like
SQL
WITH Cars (CategoryProductID, Text, Parents)
AS (
    SELECT CategoryProductID, CategoryText, CategoryText
    FROM tSameCategoryProducts
    WHERE CategoryProductID = 1
    UNION ALL
    SELECT CategoryProductID, CategoryText, Parents + '/' + CategoryText
    FROM tSameCategoryProducts t inner join cars c
         on t.CategoryProductParentID = c.CategoryProductID
)
SELECT Text, Parents
FROM Cars


For more information see Recursive Queries Using Common Table Expressions[^]
 
Share this answer
 
Comments
arminamini 26-May-12 5:48am    
Many Thanks.
Wendelius 1-Jun-12 0:30am    
You're welcome :)
Monjurul Habib 26-May-12 15:49pm    
5!
Wendelius 1-Jun-12 0:30am    
Thanks :)
Maciej Los 29-May-12 5:00am    
Good work, Mika ;)
+5!

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