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
There are two types of Common Table Expression, Non-Recursive CTE - It does not have any reference to itself in the CTE definition. Recursive CTE - When a CTE has reference in itself, then it's called recursive CTE.
A recursive query is one that is defined by a Union All with an initialization fullselect that seeds the recursion. The iterative fullselect contains a direct reference to itself in the FROM clause. There are additional restrictions as to what can be specified in the definition of a recursive query.
A recursive CTE references itself. It returns the result subset, then it repeatedly (recursively) references itself, and stops when it returns all the results. The syntax for a recursive CTE is not too different from that of a non-recursive CTE: WITH RECURSIVE cte_name AS ( cte_query_definition (the anchor member)
A recursive CTE is a CTE that references itself. In doing so, the initial CTE is repeatedly executed, returning subsets of data, until the complete result is returned.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With