ここでは、再帰的な共通テーブル式を使用した完全な実例があります。
DECLARE @categories TABLE
(
ID INT NOT NULL,
[Name] VARCHAR(50),
Parent INT NULL
);
INSERT INTO @categories VALUES (4, 'Free Stuff', NULL);
INSERT INTO @categories VALUES (1, 'Hardware', NULL);
INSERT INTO @categories VALUES (3, 'Movies', NULL);
INSERT INTO @categories VALUES (2, 'Software', NULL);
INSERT INTO @categories VALUES (10, 'a', 0);
INSERT INTO @categories VALUES (12, 'apples', 2);
INSERT INTO @categories VALUES (8, 'catD', 2);
INSERT INTO @categories VALUES (9, 'catE', 2);
INSERT INTO @categories VALUES (5, 'catA', 3);
INSERT INTO @categories VALUES (6, 'catB', 3);
INSERT INTO @categories VALUES (7, 'catC', 3);
INSERT INTO @categories VALUES (11, 'aa2', 4);
WITH categories(ID, Name, Parent, HierarchicalName)
AS
(
SELECT
c.ID
, c.[Name]
, c.Parent
, CAST(c.[Name] AS VARCHAR(200)) AS HierarchicalName
FROM @categories c
WHERE c.Parent IS NULL
UNION ALL
SELECT
c.ID
, c.[Name]
, c.Parent
, CAST(pc.HierarchicalName + c.[Name] AS VARCHAR(200))
FROM @categories c
JOIN categories pc ON c.Parent = pc.ID
)
SELECT c.*
FROM categories c
ORDER BY c.HierarchicalName
はもしかしてその: 無料で譲り AA2 ハードウェア 作品 CATA 等... ? –