sql >> Base de Datos >  >> RDS >> Sqlserver

Seleccione todos los padres o hijos en la misma relación de tabla SQL Server

Me encontré con este problema, lo resolví de esta manera

 --all  "parent + grandparent + etc" @childID Replaced with the ID you need

with tbParent as
(
   select * from Elem where [KEY][email protected]
   union all
   select Elem.* from Elem  join tbParent  on Elem.[KEY]=tbParent.PARENT_KEY
)
 SELECT * FROM  tbParent
 --all "sons + grandsons + etc" @parentID Replaced with the ID you need

with tbsons as
(
  select * from Elem where [KEY][email protected]
  union all
  select Elem.* from Elem  join tbsons  on Elem.PARENT_KEY=tbsons.[KEY]
)
SELECT * FROM tbsons

PD.Mi inglés no es bueno.