Ну, это уродливо и предполагает, что у вас максимум 15 уровней, и ваши ожидаемые результаты неверны;как у меня W_ID
4
имеет значение 'DSO'
для Level_3
, но ваши ожидаемые результаты имеют CX
, хотя эта строка никак не связана с CX
.
USE Sandbox;
GO
CREATE TABLE dbo.YourTable (W_ID int NOT NULL,
Title varchar(3) NOT NULL,
Parent_id int NULL,
View_Parent_id varchar(100) NULL);
GO
INSERT INTO dbo.YourTable
VALUES (1,'AAA',NULL,NULL),
(2,'BV',1,'1'),
(3,'CX',2,'1+2'),
(4,'DSO',2,'1+2'),
(5,'ER',3,'1+2+3'),
(6,'ER',5,'1+2+3+5');
GO
SELECT *
FROM dbo.YourTable;
GO
WITH rCTE AS(
SELECT (YT.W_ID + 99) AS ID,
YT.W_ID ,
YT.Parent_id,
Title AS level_1,
CONVERT(varchar(3),NULL) AS Level_2,
CONVERT(varchar(3),NULL) AS Level_3,
CONVERT(varchar(3),NULL) AS Level_4,
CONVERT(varchar(3),NULL) AS Level_5,
CONVERT(varchar(3),NULL) AS Level_6,
CONVERT(varchar(3),NULL) AS Level_7,
CONVERT(varchar(3),NULL) AS Level_8,
CONVERT(varchar(3),NULL) AS Level_9,
CONVERT(varchar(3),NULL) AS Level_10,
CONVERT(varchar(3),NULL) AS Level_11,
CONVERT(varchar(3),NULL) AS Level_12,
CONVERT(varchar(3),NULL) AS Level_13,
CONVERT(varchar(3),NULL) AS Level_14,
CONVERT(varchar(3),NULL) AS Level_15,
1 AS [Level]
FROM dbo.YourTable YT
WHERE YT.Parent_id IS NULL
UNION ALL
SELECT (YT.W_ID + 99) AS ID,
YT.W_ID,
YT.Parent_id,
r.Level_1,
CASE r.[Level] WHEN 1 THEN YT.Title ELSE r.Level_2 END AS Level_2,
CASE r.[Level] WHEN 2 THEN YT.Title ELSE r.Level_3 END AS Level_3,
CASE r.[Level] WHEN 3 THEN YT.Title ELSE r.Level_4 END AS Level_4,
CASE r.[Level] WHEN 4 THEN YT.Title ELSE r.Level_5 END AS Level_5,
CASE r.[Level] WHEN 5 THEN YT.Title ELSE r.Level_6 END AS Level_6,
CASE r.[Level] WHEN 6 THEN YT.Title ELSE r.Level_7 END AS Level_7,
CASE r.[Level] WHEN 7 THEN YT.Title ELSE r.Level_8 END AS Level_8,
CASE r.[Level] WHEN 8 THEN YT.Title ELSE r.Level_9 END AS Level_9,
CASE r.[Level] WHEN 9 THEN YT.Title ELSE r.Level_10 END AS Level_10,
CASE r.[Level] WHEN 10 THEN YT.Title ELSE r.Level_11 END AS Level_11,
CASE r.[Level] WHEN 11 THEN YT.Title ELSE r.Level_12 END AS Level_12,
CASE r.[Level] WHEN 12 THEN YT.Title ELSE r.Level_13 END AS Level_13,
CASE r.[Level] WHEN 13 THEN YT.Title ELSE r.Level_14 END AS Level_14,
CASE r.[Level] WHEN 14 THEN YT.Title ELSE r.Level_15 END AS Level_15,
r.[Level] + 1 AS [Level]
FROM dbo.YourTable YT
JOIN rCTe r ON YT.Parent_id = r.W_ID)
SELECT r.ID,
r.W_ID,
r.Parent_id,
r.Level_1,
r.Level_2,
r.Level_3,
r.Level_4,
r.Level_5,
r.Level_6,
r.Level_7,
r.Level_8,
r.Level_9,
r.Level_10,
r.Level_11,
r.Level_12,
r.Level_13,
r.Level_14,
r.Level_15
FROM rCTE r;
GO
DROP TABLE dbo.YourTable;
дБ <> скрипка