7

カテゴリ@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".

助けてくれてありがとう

4

1 に答える 1

10

クエリを変更して、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
于 2013-08-07T18:17:41.447 に答える