CTE 查询 SQL 服务器中的解析错误

Parsing error in in CTE query SQL server

我编写了一个 CTE 查询,我正在 Microsoft SQL Server 2008 R2 Management Studio 中执行该查询:

WITH DependencyHierarchy(processName, dependProcessName) AS
(
    SELECT
       processName,
       dependProcessName,
       1 as HierarchyLevel
    FROM processDependency

    UNION ALL

    SELECT
        e.processName,
        e.dependProcessName,
        eh.HierarchyLevel + 1 AS HierarchyLevel
    FROM 
        processDependency e
    INNER JOIN 
        DependencyHierarchy eh ON e.dependProcessName = eh.processName
)
SELECT *
FROM DependencyHierarchy
ORDER BY HierarchyLevel, processName, dependProcessName;
GO

它抛出这个错误:

There was an error parsing the query. [ Token line number = 1,Token line offset = 1,Token in error = WITH ]

table 有这个数据:

    processName dependProcessName
    P1          P2
    P2          P3
    P3          P4
    P4          P5
    P6          P7

WITH common_table_expression:

column_name

Specifies a column name in the common table expression. Duplicate names within a single CTE definition are not allowed. The number of column names specified must match the number of columns in the result set of the CTE_query_definition.

The list of column names is optional only if distinct names for all resulting columns are supplied in the query definition.

将第 HierarchyLevel 列添加到 cte 列列表:

WITH DependencyHierarchy(processName,dependProcessName, HierarchyLevel)
AS
(
   ...
)

LiveDemo

或将其留空(列名将派生自第一个 SELECT):

WITH DependencyHierarchy AS
(
   ...
)

LiveDemo2