Types don't match between the anchor and the recursive part in column of recursive query

13,233

Try changing the query to cast the varchars to VARCHAR(MAX).

Something like

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
Share:
13,233
Richard77
Author by

Richard77

Updated on June 19, 2022

Comments

  • Richard77
    Richard77 almost 2 years

    Given a category @categoryId, the query should recursively navigate to the top most super-category, which has been accomplished.

    Now I'd like also to generate all along a string which would be the concatenation of all the CategoryName in the process.

    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
    

    With the above code I'm getting the following error:

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

    Thanks for helping