4

i'm trying to concatenate the values from a column from all levels of a certain path

this is my sql:

WITH
hi as (
select c.id id, cast(c.code as nvarchar) code, c.title, c.parent from CaseTypes c 
where c.parent is null

union all

select c.id, cast((h.code + c.code ) as nvarchar) code , c.title, c.parent from CaseTypes c 
inner join hi h on c.parent = h.id
)
select * from hi

the problem is that only the first level (where parent is null) is taken, the rest isn't

1
  • I just ran your exact code on a test table and it seems to work fine. Commented Jul 27, 2011 at 14:40

1 Answer 1

6

This code will concatenate the string and only display the last parent

declare @CaseTypes table (
    code nvarchar(max),
    title varchar(20),
    parent int, id int
)

insert @CaseTypes values ('a', 't1', null, 1)
insert @CaseTypes values ('b', 't2',    1, 2)
insert @CaseTypes values ('c', 't3',    2, 3)

;with hi as (

    select c.id id, cast(c.code as nvarchar) code, c.title, c.parent 
    from @CaseTypes c 
    where c.parent is null

    union all

    select c.id, cast((h.code + c.code ) as nvarchar) code, c.title, c.parent
    from @CaseTypes c 
    inner join hi h on c.parent = h.id
)

select id, code, title, parent 
from hi h 
where not exists (
    select 1
    from hi
    where h.id = parent
)
Sign up to request clarification or add additional context in comments.

5 Comments

Not really much change, but sometimes the problems we are faceing are hard to spot.
it's no change at all actually, but at least I know that the problem is in something else
there is a change, I picked the right row. I was assuming your code only picked one of the rows from the result
my problem is in the concatenation, in your example if doing select * at the end you will get for code a, ab, abc (3 rows) as with my table i get just 'a' (code of the first parent) for all the rows
I took your exact code and tried, I get a,ab,abc with your exact code. I think you should take a look at your id and parent for your data, I bet the problem is there.

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.