gpt4 book ai didi

sql - 递归查询列中的 anchor 和递归部分之间的类型不匹配

转载 作者:行者123 更新时间:2023-12-02 23:05:09 49 4
gpt4 key购买 nike

给定一个类别@categoryId,查询应递归导航到最顶层的 super 类别,这已完成。

现在我还想生成一个字符串,该字符串将是过程中所有 CategoryName 的串联。

DECLARE @CategoryId AS int = 217;
WITH Categories AS
(
SELECT ParentCategoryId, CategoryName, '' AS strCategory
FROM Category
WHERE CategoryId = @CategoryId

UNION ALL

SELECT c.ParentCategoryId, c.CategoryName,
(c.CategoryName + ': ' + cts.strCategory) AS strCategory
FROM Category AS c
JOIN Categories AS cts
ON c.CategoryId = cts.ParentCategoryId
)

SELECT TOP 1 CategoryName, LEN(CategoryName) AS strLength
FROM Categories
ORDER BY strLength DESC

使用上面的代码我收到以下错误:

Types don't match between the anchor and the recursive part in column 
"strCategory" of recursive query "Categories".

感谢您的帮助

最佳答案

尝试更改查询以将 varchar 转换为 VARCHAR(MAX)。

类似于

DECLARE @CategoryId AS int = 217;
WITH Categories AS
(
SELECT ParentCategoryId, CategoryName, CAST('' AS VARCHAR(MAX)) AS strCategory
FROM Category
WHERE CategoryId = @CategoryId

UNION ALL

SELECT c.ParentCategoryId, c.CategoryName,
CAST((c.CategoryName + ': ' + cts.strCategory) AS VARCHAR(MAX)) AS strCategory
FROM Category AS c
JOIN Categories AS cts
ON c.CategoryId = cts.ParentCategoryId
)

SELECT TOP 1 CategoryName, LEN(CategoryName) AS strLength
FROM Categories
ORDER BY strLength DESC

关于sql - 递归查询列中的 anchor 和递归部分之间的类型不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18110730/

49 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com