NULLです。子供なしの保護者は表示されません。ここで
DECLARE @ProjectCategories TABLE
(
categoryid INT,
categoryname VARCHAR(10),
projectid INT,
parentcategoryid INT,
sortorder INT
)
INSERT INTO @ProjectCategories
SELECT 1, 'Main1', 1, null, 1 UNION ALL
SELECT 2, 'Child1', 1, 1, 1 UNION ALL
SELECT 3, 'Child2', 1, 2, 1 UNION ALL
SELECT 4, 'Child3', 1, 3, 1 UNION ALL
SELECT 5, 'Child4', 1, 4, 1 UNION ALL
SELECT 6, 'MainA', 2, null, 1 UNION ALL
SELECT 7, 'ChildA', 2, 6, 1 UNION ALL
SELECT 8, 'ChildB', 2, 7, 1 UNION ALL
SELECT 9, 'Main!', 3, null, 1
SELECT *
FROM @ProjectCategories Child
INNER JOIN @ProjectCategories Parent
ON Child.parentcategoryid = Parent.categoryid
AND Parent.parentcategoryid IS NULL
すべての親は関係なく、子供たちが存在する場合は、次のとおりです。
DECLARE @ProjectCategories TABLE
(
categoryid INT,
categoryname VARCHAR(10),
projectid INT,
parentcategoryid INT,
sortorder INT
)
INSERT INTO @ProjectCategories
SELECT 1, 'Main1', 1, null, 1 UNION ALL
SELECT 2, 'Child1', 1, 1, 1 UNION ALL
SELECT 3, 'Child2', 1, 2, 1 UNION ALL
SELECT 4, 'Child3', 1, 3, 1 UNION ALL
SELECT 5, 'Child4', 1, 4, 1 UNION ALL
SELECT 6, 'MainA', 2, null, 1 UNION ALL
SELECT 7, 'ChildA', 2, 6, 1 UNION ALL
SELECT 8, 'ChildB', 2, 7, 1 UNION ALL
SELECT 9, 'Main!', 3, null, 1
SELECT *
FROM @ProjectCategories Parent
WHERE Parent.parentcategoryid IS NULL
はここに関係なく、そこにどのように多くの子供たちの親のための子供のすべてを取得しないであろう、再帰CTEです。
DECLARE @ProjectCategories TABLE
(
categoryid INT,
categoryname VARCHAR(10),
projectid INT,
parentcategoryid INT,
sortorder INT
)
INSERT INTO @ProjectCategories
SELECT 1, 'Main1', 1, null, 1 UNION ALL
SELECT 2, 'Child1', 1, 1, 1 UNION ALL
SELECT 3, 'Child2', 1, 2, 1 UNION ALL
SELECT 4, 'Child3', 1, 3, 1 UNION ALL
SELECT 5, 'Child4', 1, 4, 1 UNION ALL
SELECT 6, 'MainA', 2, null, 1 UNION ALL
SELECT 7, 'ChildA', 2, 6, 1 UNION ALL
SELECT 8, 'ChildB', 2, 7, 1 UNION ALL
SELECT 9, 'Main!', 3, null, 1
;WITH Projects
(
categoryid,
categoryname,
parentcategoryid
)
AS
(
-- Base Case
SELECT categoryid,
categoryname,
parentcategoryid
FROM @ProjectCategories
WHERE projectid = 1 -- Change this to 1, 2, or 3
AND parentcategoryid IS NULL
UNION ALL
-- Recursive
SELECT pc.categoryid,
pc.categoryname,
pc.parentcategoryid
from Projects
INNER JOIN @ProjectCategories pc
ON pc.parentcategoryid = Projects.categoryid
)
SELECT * from Projects
再帰的なCTEの匂いがします。誰かがそれを最初にやっていないと私が家に帰ると、私はそれをやります。 – SQLMason
カーソルを動かす! – JonH
親 - >子階層に複数のレベルがある場合は、各子の最下位レベルの親だけを必要としますか? – JNK