Skip to content
Advertisement

Generate a Complete List of Parent-Child IDs in Single Column Using SQL

I have seen numerous examples on this, but none do exactly what I need…and I am having a hard time figuring it out. (all the examples I see list the results in 2 columns…I don’t need that)

I have a table named ‘Documents’ with 2 columns

  • Id
  • ParentId (nullable)

Like so…

Populated as such…

I need to recursively traverse the parent-child relationship (until NULL) & get a list of all the Id’s into a single column, like so…

enter image description here

Advertisement

Answer

(I assume based on syntax that you are using SQL Server.)

You can use a recursive CTE:

Here is a SQL Fiddle.

Note: You cannot insert (normally) into a column declared as identity. If you want to put in the values, remove the identity() attribute.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement