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 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
|
CREATE TABLE #Titres (
TitreId int,
PrecedentId int,
Niveau tinyint,
Libelle varchar(50)
)
INSERT INTO #Titres VALUES (10, 0, 1, 'Plantes')
INSERT INTO #Titres VALUES (13, 10, 2, 'Fleurs')
INSERT INTO #Titres VALUES (22, 13, 1, 'Animaux')
INSERT INTO #Titres VALUES (24, 22, 2, 'Chiens')
GO
CREATE TABLE #Articles (
ArticleId int,
TitreId int,
Libelle varchar(50),
Ordre tinyint
)
INSERT INTO #Articles VALUES (1, 13, 'Ancolie', 2)
INSERT INTO #Articles VALUES (2, 13, 'Roses', 1)
INSERT INTO #Articles VALUES (3, 24, 'Boxer', 1)
INSERT INTO #Articles VALUES (4, 24, 'Berger A.', 2)
GO
;WITH cte1 AS (
SELECT
t.TitreId, t.PrecedentId, t.Libelle, 1000 as Ordre, Niveau
FROM #Titres t
WHERE PrecedentId = 0
UNION ALL
SELECT t.TitreId, t.PrecedentId, t.Libelle, c.Ordre + 1000 as Ordre, t.Niveau
FROM #Titres t
JOIN cte1 c ON t.PrecedentId = c.TitreId
)
SELECT
--ROW_NUMBER() OVER (ORDER BY t.Ordre, a.Ordre) as id,
-- CAST(ROW_NUMBER() OVER (ORDER BY TitreId) as varchar(20)) as Numero
t.Ordre,
t.Niveau,
SPACE(t.Niveau * 2) + t.Libelle
FROM cte1 t
UNION ALL
SELECT
a.Ordre + t.Ordre,
t.Niveau + 1 as Niveau,
SPACE((t.Niveau + 1) * 2) + a.Libelle
FROM #Articles a
JOIN cte1 t ON t.TitreId = a.TitreId
ORDER BY Ordre; |
Partager