有一个描述对象层次结构及其类型的表:
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 中有一个过滤器。