I'm trying to add a WITH
clause to a statement within a scalar function but when I do, I get the following syntax errors:
SQL80001: Incorrect syntax near 'WITH'
SQL80001: Incorrect syntax near ')'
The last error refers to the final closing bracket.
Here a greatly-simplified example of the SQL which also fails for the same reason:
CREATE FUNCTION IsSumEqualToTen
(
@number1 INT,
@number2 INT
)
RETURNS BIT
AS
BEGIN
RETURN
(
WITH AddNumbers AS
(
SELECT @number1 + @number2
)
SELECT CASE WHEN AddNumbers = 10
THEN 1
ELSE 0
END
)
END
I know that when changed to this, it has no syntax errors:
CREATE FUNCTION IsSumEqualToTen
(
@number1 INT,
@number2 INT
)
RETURNS BIT
AS
BEGIN
RETURN
(
CASE WHEN (@number1 + @number2) = 10
THEN 1
ELSE 0
END
)
END
But for what I'm actually doing I need a recursive CTE to flatten a heirarchy so the WITH
is essential.