【问题标题】:Types don't match between the anchor and the recursive part in column of recursive query递归查询列中的锚点和递归部分的类型不匹配
【发布时间】:2013-08-07 18:14:44
【问题描述】:

给定一个类别 @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".

感谢您的帮助

【问题讨论】:

    标签: sql sql-server tsql


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2018-09-30
      • 2014-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-10
      • 2019-05-01
      • 2010-12-22
      • 1970-01-01
      相关资源
      最近更新 更多