3

I have a simple categories table as with the following columns:

  • Id
  • Name
  • ParentId

So, an infinite amount of Categories can be the child of a category. Take for example the following hierarchy:

enter image description here

I want, in a simple query that returns the category "Business Laptops" to also return a column with all it's parents, comma separator or something:

enter image description here

Or take the following example:

enter image description here

3
  • Have a look: dba.stackexchange.com/questions/160924/… Commented Mar 22, 2017 at 15:08
  • One important clarifying question: Will a category always only have one parent? Commented Mar 22, 2017 at 15:09
  • @LaughingVergil: It will never have more than one direct parent, but it could also have no parent. Commented Mar 23, 2017 at 8:09

1 Answer 1

13

Recursive cte to the rescue....

Create and populate sample table (Please save us this step in your future questions):

DECLARE @T as table
(
    id int,
    name varchar(100),
    parent_id int
)

INSERT INTO @T VALUES
(1, 'A', NULL),
(2, 'A.1', 1),
(3, 'A.2', 1),
(4, 'A.1.1', 2),
(5, 'B', NULL),
(6, 'B.1', 5),
(7, 'B.1.1', 6),
(8, 'B.2', 5),
(9, 'A.1.1.1', 4),
(10, 'A.1.1.2', 4)

The cte:

;WITH CTE AS
(
    SELECT id, name, name as path, parent_id
    FROM @T 
    WHERE parent_id IS NULL
    UNION ALL
    SELECT t.id, t.name, cast(cte.path +','+ t.name as varchar(100)), t.parent_id
    FROM @T t
    INNER JOIN CTE ON t.parent_id = CTE.id
)

The query:

SELECT id, name, path
FROM CTE

Results:

id      name        path
1       A           A
5       B           B
6       B.1         B,B.1
8       B.2         B,B.2
7       B.1.1       B,B.1,B.1.1
2       A.1         A,A.1
3       A.2         A,A.2
4       A.1.1       A,A.1,A.1.1
9       A.1.1.1     A,A.1,A.1.1,A.1.1.1
10      A.1.1.2     A,A.1,A.1.1,A.1.1.2

See online demo on rextester

Sign up to request clarification or add additional context in comments.

1 Comment

@ZoharPeled: awesome. I wasn't expecting such a complete answer. I will certainly in the future include sample data. Following is the query in action with some of my actual data: link

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.