Change a CTE SELECT to a table value user defined

2019-05-31 13:47发布

问题:

In an earlier post, I constructed a SQL that uses a CTE with the help from a SO contributor. I'd like now to encapsulate that SQL in a user defined function that returns a table but I am getting the error below.

Here's the code:

Alter FUNCTION GetDescendentSteps 
(   
@StepId INT 
)
RETURNS TABLE 
AS
RETURN
    ;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;

I get the error:

Msg 102, Level 15, State 1, Procedure GetDescendentSteps, Line 8
Incorrect syntax near ';'.

Note that line 8 is:

;WITH cteRecursion

..and that if I execute only the SQL beginning at line 8 (after I replace the variable @StepId with a literal).

Also, this simple example works:

ALTER FUNCTION GetDescendentSteps 
(   
@StepId INT 
)

RETURNS TABLE 

AS
RETURN
select 7 As Stepid,1 As Level

回答1:

Remove the first ; and the order by clause.

Alter FUNCTION GetDescendentSteps 
(   
@StepId INT 
)
RETURNS TABLE 
AS
RETURN
    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