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

时间:2013-08-07 18:14:44

标签: sql sql-server tsql

鉴于类别 @categoryId ,查询应递归导航到已完成的最顶级超类别。

现在我还希望生成一个字符串,该字符串将是流程中所有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".

感谢您的帮助

1 个答案:

答案 0 :(得分:6)

尝试更改查询以将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