Domanda

Say Ho una tabella di elementi che rappresentano un data strutturato ad albero, e desidero tracciare continuamente verso l'alto fino a ottenere al nodo superiore, caratterizzato da un parent_id NULL. Che cosa sarebbe la mia MS SQL CTE (espressione di tabella comune) assomigliare?

Per esempio, se dovessi ottenere il percorso per arrivare al top da Bender , sarebbe simile

Commedia

Futurama

Bender

Grazie, ed ecco i dati di esempio:

DECLARE @t Table(id int, description varchar(50), parent_id int)

INSERT INTO @T 
SELECT 1, 'Comedy', null UNION 
SELECT 2, 'Futurama', 1 UNION
SELECT 3, 'Dr. Zoidberg', 2 UNION 
SELECT 4, 'Bender', 2 UNION
SELECT 5, 'Stand-up', 1 UNION
SELECT 6, 'Unfunny', 5 UNION
SELECT 7, 'Dane Cook', 6
È stato utile?

Soluzione

dovrebbe assomigliare a questo:

declare @desc varchar(50)
set @desc = 'Bender'

;with Parentage as
(
    select * from @t where description = @desc
    union all

    select t.* 
    from @t t
    inner join Parentage p
        on t.id = p.parent_id
)
select * from Parentage
order by id asc --sorts it root-first 
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top