I am trying to make an SQL Function that returns a nvarchar(MAX) string. The function uses a CTE recursive WITH statement. I can get all the parts to work correctly when they are not in the function but when I put them all together I get the following error:
Msg 208, Level 16, State 1, Line 1
Invalid object name ‘drillUp’.
The function itself does not give an error during “Compile” but only when it is run.
If I change the SET @RET to “TESTING…” instead of calling the SELECT statement it runs as expected.
I am fairly new to SQL and I am not sure what I am doing wrong. If anyone can give me some advice I would greatly appreciate it.
Thank you.
Joe
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)
CTE’s are only valid to be used on the statement that follows his definition. So you should move your
SET @RETto be next the definition ofdrillup: