答案 0 :(得分:1)
试试这个:
DECLARE @DataSource TABLE
(
[FolderID] INT
,[FolderName] VARCHAR(12)
,[ParentID] INT
);
INSERT INTO @DataSource ([FolderID], [FolderName], [ParentID])
VALUES (10011, 'NEw Folder', NULL)
,(10012, 'NEw Folder', 10011)
,(10013, 'NEw Folder', 10012)
,(10014, 'NEw Folder', 10013)
,(10021, 'NEw Folder', NULL)
,(10022, 'NEw Folder', 10021)
,(10023, 'NEw Folder', 10022);
DECLARE @ParentID INT = 10011;
WITH DataSource AS
(
SELECT *
FROM @DataSource
WHERE [FolderID] = @ParentID
UNION ALL
SELECT A.*
FROM DataSource R
INNER JOIN @DataSource A
ON R.[FolderID] = A.[ParentID]
)
SELECT DISTINCT [FolderID]
FROM DataSource
WHERE [FolderID] <> @ParentID;
答案 1 :(得分:0)
使用递归cte
;WITH cte
AS
( SELECT
b.FolderId, b.FolderName, b.ParentiD
FROM
table b
WHERE
FolderId= 10011
UNION ALL
SELECT
e.FolderId, e.FolderName, e.ParentId
FROM
table e
INNER JOIN
cte r ON e.ParentId = r.FodlerId
)
SELECT * FROM cte
答案 2 :(得分:0)
简单的自我加入会帮助你
select e.folderid from table1 e inner join table1 t on e.parentid = t.folderid where t.parentid = 10011
尝试以上查询:)