You did not specify your DBMS, so I assume PostgreSQL
WITH RECURSIVE fam_tree (id, name, parent, family) as ( SELECT id, name, parentid, ''::text as family FROM the_unknown_table WHERE parent IS NULL UNION ALL SELECT t2.id, t2.name, t2.parentid, fam_tree.family || '^' || t2.name FROM the_unknown_table t2 INNER JOIN fam_tree ON fam_tree.id = t2.parentid ) SELECT * FROM fam_tree;
This is standard SQL (with the exception of the ::text
method), which should work with very small changes in most modern DBMSs.
Edit
For SQL Server, you need to replace the standard concatenation character with the non-standard Microsoft +
character (and you need to remove the recursive
keyword, which is required by the standard, but for some strange reason rejected by SQL Server)
WITH fam_tree (id, name, parent, family) as ( SELECT id, name, parentid, '' as family FROM the_unknown_table WHERE parent IS NULL UNION ALL SELECT t2.id, t2.name, t2.parentid, fam_tree.family + '^' + t2.name FROM the_unknown_table t2 INNER JOIN fam_tree ON fam_tree.id = t2.parentid ) SELECT * FROM fam_tree;
source share