1

有一个描述对象层次结构及其类型的表:

DECLARE @TTable TABLE
(
 ID int
 ,Higher int -- for some reason this is how ID_PARENT named
 ,[Type] int
)

我需要选择一个子树,其分支只包含某些 [Type] 的节点。由于我通常是 SQL 和 CTE 的初学者,因此我首先从下到上查找包含某种类型的对象的所有分支:

;WITH c
AS
(
SELECT 
    ID
    ,Higher
    ,[Type]
FROM
    dbo.EnObj
WHERE Type = 40

UNION ALL

SELECT
    t.ID
    ,t.Higher
    ,t.Type
FROM
    dbo.EnObj T
INNER JOIN c ON t.ID = c.Higher
)

然后将唯一记录选择到表变量中:

INSERT @TTable
SELECT DISTINCT
c.ID
,c.Higher
,c.Type
,c.Name
,c.Voltage
FROM  c

然后通过 CTE 构建一个层次结构,从上到下排序:

;WITH CTE AS (
    SELECT
    ID
    ,Higher
    ,[Type]
,CAST(ID AS VARCHAR(128)) AS Sort
FROM    
    @TTable
WHERE
    Higher IS NULL
UNION ALL
SELECT
    N.ID
    ,N.Higher
    ,N.[Type]
    ,CAST(P.Sort + '/' + CAST(N.ID AS VARCHAR) AS VARCHAR(128))
FROM    
    @TTable N
INNER JOIN CTE AS P ON P.ID = N.Higher
)
SELECT 
    ID
    ,Higher
    ,[Type]
    ,Sort
FROM CTE 
ORDER BY Sort

它有效,但我想知道是否有办法优化这个查询,比如使用一个 CTE 而不是两个,或者在 CTE 中有一个过滤器。

4

1 回答 1

1
with Hierachy 
as  
(
    select ID, Higher, Type from EnObj
        WHERE Type = 40 -- Whatever your search criteria

        union all   
    select EnObj.ID, EnObj.Higher ,EnObj.Type from EnObj    
    inner join Hierachy 
    on tblOrgLevel.Higher = Hierachy.ID
 )
select * from Hierachy --where ID <> 40  

另一种解决方案

WITH DirectReports
AS 
(
    SELECT parentid, id, Title, 0 AS EmployeeLevel
    FROM dbo.tblOrgLevel  
    WHERE ISNULL(parentid ,0) = 0 and  FKAgencyID = 58
    UNION ALL
    SELECT e.parentid, e.id, e.Title, EmployeeLevel + 1
    FROM dbo.tblOrgLevel AS e
        INNER JOIN DirectReports AS d
        ON e.parentid= d.id 
)
SELECT *
FROM DirectReports
ORDER BY parentid;
GO

您可以要求我进行更多说明和一些修改

于 2013-09-20T14:45:10.477 回答