Sql server 查找具有hierarchyid子节点的所有节点

Sql server 查找具有hierarchyid子节点的所有节点,sql-server,tsql,hierarchyid,Sql Server,Tsql,Hierarchyid,鉴于此表: CREATE TABLE Employee ( EmpId INT PRIMARY KEY IDENTITY, EmpName VARCHAR(100) NOT NULL, Position HierarchyID NOT NULL ) INSERT INTO Employee (EmpName, Position) VALUES ('CEO', '/'), ('COO', '/1/'), ('CIO', '/2/'), ('CFO'

鉴于此表:

CREATE TABLE Employee
(
    EmpId INT PRIMARY KEY IDENTITY,
    EmpName VARCHAR(100) NOT NULL,
    Position HierarchyID NOT NULL
)

INSERT INTO Employee (EmpName, Position)
VALUES ('CEO', '/'),
    ('COO', '/1/'),
    ('CIO', '/2/'),
    ('CFO', '/3/'),
    ('VP Financing', '/3/1/'),
    ('Accounts Receivable', '/3/1/1/'),
    ('Accountant 1', '/3/1/1/1/'),
    ('Accountant 2', '/3/1/1/2/'),
    ('Accountant 3', '/3/1/1/3/'),
    ('Accounts Payable', '/3/1/2/'),
    ('Accountant 4', '/3/1/2/1/'),
    ('Accountant 5', '/3/1/2/2/'),
    ('DBA', '/2/1/'),
    ('VP of Operations', '/1/1/')
如何查找没有任何子节点的所有行

我有以下几点似乎有效,但似乎应该有一种不那么复杂的方法:

select * from (
    select 
        *,  
        case 
            when (select top 1 e.Position from dbo.Employee e where Position.GetAncestor(1) = Employee.Position) is null then 
                cast (0 as bit)
            else 
                cast (1 as bit)
        end as HasDescendants     
    from 
        dbo.Employee
) as managers
where HasDescendants = 0

请参阅另一个堆栈溢出问题:


请参阅另一个堆栈溢出问题:

查询:

SELECT e.*
FROM dbo.Employee e
WHERE NOT EXISTS (SELECT 0
       FROM Employee e2
       WHERE e2.Position.ToString() like e.Position.ToString() + '_%')
结果:

| EMPID |          EMPNAME |    POSITION |
------------------------------------------
|     7 |     Accountant 1 | 122,-42,-80 |
|     8 |     Accountant 2 | 122,-42,-48 |
|     9 |     Accountant 3 | 122,-42,-16 |
|    11 |     Accountant 4 | 122,-38,-80 |
|    12 |     Accountant 5 | 122,-38,-48 |
|    13 |              DBA |     106,-64 |
|    14 | VP of Operations |      90,-64 |
查询:

SELECT e.*
FROM dbo.Employee e
WHERE NOT EXISTS (SELECT 0
       FROM Employee e2
       WHERE e2.Position.ToString() like e.Position.ToString() + '_%')
结果:

| EMPID |          EMPNAME |    POSITION |
------------------------------------------
|     7 |     Accountant 1 | 122,-42,-80 |
|     8 |     Accountant 2 | 122,-42,-48 |
|     9 |     Accountant 3 | 122,-42,-16 |
|    11 |     Accountant 4 | 122,-38,-80 |
|    12 |     Accountant 5 | 122,-38,-48 |
|    13 |              DBA |     106,-64 |
|    14 | VP of Operations |      90,-64 |