2

给定以下架构和数据:

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
4

2 回答 2

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上的演示

于 2013-01-17T23:51:24.243 回答
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)

这几乎是我在这里找到的答案的直接副本。

于 2013-01-17T22:48:17.757 回答