Reputation: 9453
Given the following schema and data:
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')
How can I get the following result:
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
Upvotes: 2
Views: 1337
Reputation: 107508
Updated to produce a correct result:
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)
This is pretty much a straight copy of the answer I found here.
Upvotes: 0
Reputation: 16904
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
Demo on SQLFiddle
Upvotes: 3