"Incorrect syntax near the keyword 'WITH'" in a function returning XML with CTE expression
I am trying to write a function to support some (legacy) SQL code, function will be used as a part of a query:
SELECT
q.*,
fn_qncatxml(q.number, q.version) AS categories --XML aggregated category hierarchy
FROM
[dbo].[qn] q
Unfortunately following approach does not work as SQL Server has some known problems with CTE expressions in a function (semicolon before WITH solution). Unfortunately I'm not sure how to apply this solution to a function returning scalar, like this:
CREATE FUNCTION [dbo].[fn_qncatxml](@qnnumber INT, @qnversion INT)
RETURNS XML
WITH RETURNS NULL ON NULL INPUT
BEGIN
RETURN
(
WITH [categories] AS
(
SELECT [qn].[number], [qn].[version], [cat].[catnumber], [qncat].[itemnumber], [cat].[parent], [cat].[description], 0 AS [distance]
FROM [qn]
LEFT JOIN [qncat] ON [qncat].[qnnumber] = [qn].[number] AND [qncat].[qnversion] = [qn].[version]
LEFT JOIN [cat] ON [cat].[catnumber] = [qncat].[catnumber] AND [cat].[status] = '1'
开发者_高级运维 WHERE [qn].[number] = @qnnumber AND [qn].[version] = @qnversion
UNION ALL
SELECT [categories].[number], [categories].[version], [cat].[catnumber], [categories].[itemnumber], [cat].[parent], [cat].[description], [categories].[distance] + 1 AS [distance]
FROM [categories]
JOIN [cat] ON [cat].[catnumber] = [categories].[parent]
WHERE
[cat].[status] = '1'
)
SELECT DISTINCT * FROM [categories] FOR XML PATH('')
)
END
When I'll strip a part between WITH and FOR XML PATH(''), give some valid arguments and execute this block, it works perfectly.
Has anyone a clue how to make this CTE function syntax work in my scenario ?
CREATE FUNCTION [dbo].[fn_qncatxml](@qnnumber INT, @qnversion INT)
RETURNS XML
WITH RETURNS NULL ON NULL INPUT
BEGIN
DECLARE @Ret xml;
WITH [categories] AS
(
SELECT [qn].[number], [qn].[version], [cat].[catnumber], [qncat].[itemnumber], [cat].[parent], [cat].[description], 0 AS [distance]
FROM [qn]
LEFT JOIN [qncat] ON [qncat].[qnnumber] = [qn].[number] AND [qncat].[qnversion] = [qn].[version]
LEFT JOIN [cat] ON [cat].[catnumber] = [qncat].[catnumber] AND [cat].[status] = '1'
WHERE [qn].[number] = @qnnumber AND [qn].[version] = @qnversion
UNION ALL
SELECT [categories].[number], [categories].[version], [cat].[catnumber], [categories].[itemnumber], [cat].[parent], [cat].[description], [categories].[distance] + 1 AS [distance]
FROM [categories]
JOIN [cat] ON [cat].[catnumber] = [categories].[parent]
WHERE
[cat].[status] = '1'
)
SELECT @Ret = (SELECT DISTINCT * FROM [categories] FOR XML PATH(''))
RETURN @Ret
END
精彩评论