I am trying to perform what I believe is a difficult recursion using a CTE is SQL Server 2008. I can't seem to wrap my head around this one.
In the below examples you can assume a fixed depth of 3...nothing will ever be lower than that. In real life, the depth is "deeper" but still fixed. In the example I tried to simplify it some.
My input data is like the below.
ID PARENT_ID NAME DEPTH
------------------------------------------
1 NULL A 1
2 1 B 2
3 2 C 3
4 1 D 2
The output of my CTE should be the following table.
LEVEL1_ID LEVEL2_ID LEVEL3_ID LEVEL1_NAME LEVEL2_NAME LEVEL3_NAME
--------------------------------------------------------------------------------
1 NULL NULL A NULL NULL
1 2 NULL A B NULL
1 2 3 A B C
1 4 NULL A D NULL
If I can get the ID columns in the output I can certainly map to names in a lookup table.
I am open to other ways of accomplishing this as well, including using SSIS.
Not really all that hard to do:
Gives me an output of:
As a side-note: the "depth" could be easily computed by the CTE and you don't necessarily need to store that in your table (see the
Level
column I've added):I don't remember of you can do a subquery in a cte.
I don't have a copy of sql server here but you can try with this code: