开发者

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

开发者 https://www.devze.com 2023-04-11 12:18 出处:网络
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):

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.


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
        .......


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号