1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| DECLARE @T TABLE
(
ID INT,
PERE INT,
[TYPE] CHAR(1),
LABEL VARCHAR(50)
)
INSERT @T VALUES (1, NULL, 'P', 'Prise')
INSERT @T VALUES (2, 1, 'L', 'Cable')
INSERT @T VALUES (3, 2, 'P', 'Aspirateur');
INSERT @T VALUES (4, 1, 'P', 'Frigo');
INSERT @T VALUES (5, 3, 'P', 'bille');
INSERT @T VALUES (6, NULL, 'P', 'bille');
INSERT @T VALUES (7, 6, 'P', 'Robinet');
INSERT @T VALUES (8, 7, 'P', 'Boulon');
WITH CTE (ID, [TYPE], PERE, CHAINE)
AS
(
SELECT ID, [TYPE], PERE, CAST('' AS VARCHAR(MAX))
FROM @T
WHERE PERE IS NULL
UNION ALL
SELECT T.ID, T.[TYPE], T.PERE, CAST(CTE.CHAINE + CAST(T.PERE AS CHAR(1)) + ' / ' AS VARCHAR(MAX))
FROM @T AS T
INNER JOIN CTE
ON T.PERE = CTE.ID
)
SELECT
ID, [TYPE], LEFT(CHAINE, 1)
FROM CTE
WHERE TYPE = 'P'
ORDER BY ID |
Partager