ronmichael
2/5/2015 - 2:22 PM

Return all parent records in SQL hierarchy

Return all parent records in SQL hierarchy

/*
   if you have a table of rows with parent rows, this will return one row for each row and each of its parents.
   thanks to http://stackoverflow.com/questions/13487006/use-sql-server-cte-to-return-all-parent-records.
*/

with items(uniqueid,parentid) as (

	select uniqueid, uniqueid
	from equipment

	union all

	select items.uniqueid, e.parentid
	from equipment e
	inner join items on items.parentid = e.uniqueid

)

select * from items