用过滤器的MSSQL CTE树如何?

时间:2013-05-22 05:38:26

标签: sql-server filter tree common-table-expression

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

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中使用过滤器。

1 个答案:

答案 0 :(得分: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

您可以向我询问更多说明和一些修改