0

我正在尝试创建一个返回 nvarchar(MAX) 字符串的 SQL 函数。该函数使用 CTE 递归 WITH 语句。当它们不在函数中时,我可以让所有部件正常工作,但是当我把它们放在一起时,我得到以下错误:

消息 208,级别 16,状态 1,第 1 行无效的对象名称“drillUp”。

该函数本身在“编译”期间不会出错,但只有在运行时才会出错。如果我将 SET @RET 更改为“TESTING ...”而不是调用 SELECT 语句,它会按预期运行。

我对 SQL 相当陌生,我不确定我做错了什么。如果有人能给我一些建议,我将不胜感激。

谢谢你。

CREATE FUNCTION BuildName(@SUBTRAIT_ID int)
RETURNS nvarchar(MAX)
AS
BEGIN
DECLARE @RET nvarchar(MAX)
DECLARE @TEXTMODE nvarchar(50)
DECLARE @PARENTID int
DECLARE @CHECKDROPDOWN TABLE
(
    TextMode nvarchar(MAX),
    ParentId int
);

WITH drillUp(FullName, ParentId, depth) 
AS
(
    SELECT  
        SubValue,
        ParentId,
        0           
    FROM SubTrait
    WHERE Id = @SUBTRAIT_ID 
    UNION ALL
    SELECT                  
        child.SubValue + ' -> ' + drillUp.FullName,
        child.ParentId,
        drillUp.depth + 1
    FROM SubTrait child, drillUp
    WHERE drillUp.ParentId = child.Id 
)


INSERT @CHECKDROPDOWN 
SELECT TextMode, ParentId FROM SubTrait WHERE Id = @SUBTRAIT_ID

SET @TEXTMODE = (SELECT MAX(TextMode) FROM @CHECKDROPDOWN);
SET @PARENTID = (SELECT MAX(ParentId) FROM @CHECKDROPDOWN);

IF (@TEXTMODE != 'DropDown')
BEGIN
    SET @SUBTRAIT_ID = @PARENTID
END 

SET @RET = (
       SELECT FullName
       FROM drillUp du
       WHERE depth =(SELECT MAX(depth) FROM drillUp ) - 1
     )
--  SET @RET = 'TESTING...'

RETURN (@RET)

END;
GO


PRINT dbo.BuildName(77)
4

1 回答 1

1

CTE 仅适用于遵循其定义的语句。所以你应该移动你SET @RET的下一个定义drillup

CREATE FUNCTION BuildName(@SUBTRAIT_ID int)
RETURNS nvarchar(MAX)
AS
BEGIN
DECLARE @RET nvarchar(MAX)
DECLARE @TEXTMODE nvarchar(50)
DECLARE @PARENTID int
DECLARE @CHECKDROPDOWN TABLE
(
    TextMode nvarchar(MAX),
    ParentId int
);

INSERT @CHECKDROPDOWN 
SELECT TextMode, ParentId FROM SubTrait WHERE Id = 74

SET @TEXTMODE = (SELECT MAX(TextMode) FROM @CHECKDROPDOWN);
SET @PARENTID = (SELECT MAX(ParentId) FROM @CHECKDROPDOWN);

IF (@TEXTMODE != 'DropDown')
BEGIN
    SET @SUBTRAIT_ID = @PARENTID
END 

WITH drillUp(FullName, ParentId, depth) 
AS
(
    SELECT  
        SubValue,
        ParentId,
        0           
    FROM SubTrait
    WHERE Id = @SUBTRAIT_ID 
    UNION ALL
    SELECT                  
        child.SubValue + ' -> ' + drillUp.FullName,
        child.ParentId,
        drillUp.depth + 1
    FROM SubTrait child, drillUp
    WHERE drillUp.ParentId = child.Id 
)
SELECT @RET = (
       SELECT FullName
       FROM drillUp du
       WHERE depth =(SELECT MAX(depth) FROM drillUp ) - 1
     )
--  SET @RET = 'TESTING...'


RETURN (@RET)

END;
GO


PRINT dbo.BuildName(77)
于 2012-06-14T16:28:46.213 回答