1
在earlier post中,我构建了一个SQL,它在SO贡献者的帮助下使用CTE。我想现在将这个SQL封装在一个用户定义的函数中,该函数返回一个表,但是我得到下面的错误。将CTE SELECT更改为表值用户定义函数
下面的代码:
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;
我得到的错误:
Msg 102, Level 15, State 1, Procedure GetDescendentSteps, Line 8
Incorrect syntax near ';'.
注意,8号线是:
;WITH cteRecursion
..和,如果我只执行SQL从第8行开始(在我用文字替换变量@StepId之后)。
而且,这个简单的例子工程:
ALTER FUNCTION GetDescendentSteps
(
@StepId INT
)
RETURNS TABLE
AS
RETURN
select 7 As Stepid,1 As Level