Self-joining query to find descendants of a node syntax issue

萝らか妹 提交于 2019-12-08 05:13:45

问题


I have a self-linking table that records one record for every "Step" in a process (Step.ParentStepId is a foreign key to Step.StepId):

CREATE TABLE [dbo].[Step](
    [StepId] [int] IDENTITY(1,1) NOT NULL,
    [Name] [varchar](50) NOT NULL,
    [Description] [text] NULL,
    [Sequence] [int] NULL,
    [ParentStepId] [int] NULL,
 CONSTRAINT [PK_Step] PRIMARY KEY CLUSTERED 
(
    [StepId] ASC
)
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


ALTER TABLE [dbo].[Step]  WITH CHECK ADD  CONSTRAINT [FK_Step_Step] FOREIGN KEY([ParentStepId])
REFERENCES [dbo].[Step] ([StepId])

I'd like to write a query to return all of the Steps where a given StepId is a parent (at any level).

Oracle used to have some cool SQL extensions for this. How would this be done in T-SQL, SQL 2008, R2?

Here's my attempt. Help me, please, recursion too often hurts my head.

DECLARE @StepId INT = 3

WITH cteRecursion
     AS (SELECT
             Stepid
             ,1 AS Level
         FROM
             Step
         WHERE
             StepId = @StepId
         UNION ALL
         SELECT
             t.StepId
             ,c.Level + 1
         FROM
             Step t
             INNER JOIN cteRecursion c
                 ON t.ParentStepId = c.StepId
        )
SELECT
    StepId,Level
FROM
    cteRecursion
ORDER BY
    Level,
    StepId;

when run:

Msg 319, Level 15, State 1, Line 3
Incorrect syntax near the keyword 'with'. If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon.


回答1:


Read the fabulous error message!

It clearly says:

Incorrect syntax near the keyword 'with'. If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon.

So: terminate your previous statement with a semicolon, and you should be fine!

DECLARE @StepId INT = 3

; WITH cteRecursion
     AS (SELECT
             Stepid, 1 AS Level
         FROM
             Step
         WHERE
             StepId = @StepId
        .......



回答2:


You need a ; before the WITH or else you get this error.



来源:https://stackoverflow.com/questions/7679065/self-joining-query-to-find-descendants-of-a-node-syntax-issue

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