“关键字‘WITH’附近的语法不正确”在使用 CTE 表达式返回 XML 的函数中
我正在尝试编写一个函数来支持某些(旧版)SQL 代码,函数将用作查询的一部分:
SELECT
q.*,
fn_qncatxml(q.number, q.version) AS categories --XML aggregated category hierarchy
FROM
[dbo].[qn] q
不幸的是,以下方法不起作用,因为 SQL Server 在函数中的 CTE 表达式方面存在一些已知问题(WITH 之前的分号)解决方案)。不幸的是,我不确定如何将此解决方案应用于返回标量的函数,如下所示:
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
当我删除WITH和FOR XML PATH('')之间的一部分时,给出一些有效的参数并执行此块,它完美地工作。
有谁知道如何使这个 CTE 函数语法在我的场景中工作?
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 ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)