Doesn't work for me.
In my case I'm using the CTE value within the RETURN clause of a table-valued user-defined function. If I wrap the RETURN clause in BEGIN-END I get the same error message, but a bare RETURN() clause works okay. I believe the error message is incorrect in this case.
This works:
CREATE FUNCTION [dbo].[ft_SplitStringOnChar]
(
@s varchar(8000),
@sep char(1)
)
RETURNS TABLE
AS
RETURN (
WITH Pieces(pn, start, stop) AS (
SELECT 1, 1, CHARINDEX(@sep, @s)
UNION ALL
SELECT pn + 1, stop + 1, CHARINDEX(@sep, @s, stop + 1)
FROM Pieces
WHERE stop > 0
)
SELECT pn AS TokenNumber,
SUBSTRING(@s, start, CASE WHEN stop > 0 THEN stop-start ELSE 512 END) AS TokenString
FROM Pieces
)
GO
This does not:
CREATE FUNCTION [dbo].[ft_SplitStringOnChar]
(
@s varchar(8000),
@sep char(1)
)
RETURNS TABLE
AS
BEGIN
;
RETURN (
WITH Pieces(pn, start, stop) AS (
SELECT 1, 1, CHARINDEX(@sep, @s)
UNION ALL
SELECT pn + 1, stop + 1, CHARINDEX(@sep, @s, stop + 1)
FROM Pieces
WHERE stop > 0
)
SELECT pn AS TokenNumber,
SUBSTRING(@s, start, CASE WHEN stop > 0 THEN stop-start ELSE 512 END) AS TokenString
FROM Pieces
)
END
GO