Parsing error in in CTE query SQL server

怎甘沉沦 提交于 2019-12-12 17:16:24

问题


I have written a CTE query and I am executing the query in 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

It throws this error:

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

The table has this data:

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

回答1:


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.

Add column HierarchyLevel to cte column list:

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

LiveDemo

or just leave it empty (column names will be derived from first SELECT):

WITH DependencyHierarchy AS
(
   ...
)

LiveDemo2



来源:https://stackoverflow.com/questions/36429695/parsing-error-in-in-cte-query-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!