给出以下架构和数据:
CREATE TABLE ##Nodes
(
NodeCode hierarchyid,
NodeName varchar(10)
)
INSERT INTO ##Nodes VALUES ('/','RootNode')
INSERT INTO ##Nodes VALUES ('/1/','Node1')
INSERT INTO ##Nodes VALUES ('/1/1/','Node1.1')
INSERT INTO ##Nodes VALUES ('/2/','Node2')
INSERT INTO ##Nodes VALUES ('/3/','Node3')
INSERT INTO ##Nodes VALUES ('/3/1/','Node3.1')
INSERT INTO ##Nodes VALUES ('/4/','Node4')
如何获得以下结果:
NodeCode | NodeName | HasDescendants
/, RootNode, true
/1/, Node1, true,
/1/1/, Node1.1, false
/2/, Node2, false
/3/, Node3, true
/3/1/, Node3.1, false
/4/, Node4, false
答案 0 :(得分:3)
SELECT NodeCode.ToString() AS NodeCode, NodeName,
CASE WHEN (SELECT TOP 1 n.NodeCode
FROM ##Nodes
WHERE NodeCode.GetAncestor(1) = n.NodeCode) IS NULL THEN 'false'
ELSE 'true' END AS HasDescendants
FROM ##Nodes n
SQLFiddle上的演示
答案 1 :(得分:0)
更新了以产生正确的结果:
SELECT DISTINCT
n1.NodeCode.ToString()
,n1.NodeName
,(CASE WHEN n2.NodeCode IS NULL THEN 'false' ELSE 'true' END)
FROM
Nodes n1
LEFT OUTER JOIN
Nodes n2
ON
n1.NodeCode = n2.NodeCode.GetAncestor(1)
这几乎是我found here答案的直接副本。