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

Consulta recursiva para encontrar el registro principal

Prueba esto:

declare @t table (
 childID int,
 ParentID int,
 level int
)

insert into @t
select 71, 154, 4
union
select 154, 192, 3
union
select 192, 209, 2
union
select 209, 0, 1

Declare @SearchChild int
set @SearchChild=71

  ;with MyCTE as (
      select t1.childID, t1.ParentID , @SearchChild AS searchChild, t1.level
        from @t t1 
        where t1.childID = @SearchChild
      UNION ALL
      select t1.childID, t1.ParentID , c.SearchChild, t1.level
        from @t t1
        inner join MyCTE c on t1.childID=c.ParentID
  )
select top 1 * from MyCTE order by level asc

SALIDA:

childID     ParentID    searchChild level
----------- ----------- ----------- -----------
209         0           71          1

No estoy seguro de lo que buscas, ¿no hay ninguna fila que tenga 209 y 71 juntos? esto es lo mejor que puedes hacer. Además, este CTE funciona hacia arriba y no hacia abajo, y debería funcionar mucho mejor en tablas grandes.