类型与#34; ProductNames"列中的锚和递归部分之间的匹配不匹配。递归查询" CTE"

时间:2014-05-24 05:25:55

标签: sql sql-server common-table-expression

With CTE as
(
  Select ProductCategoryId,
         Count(*) [Count], 
         Max(ProductName) ProductNames, 
         0 [Rank] 
  From Product 
  Group By ProductCategoryId 

  Union ALL 

  Select CTE.ProductCategoryId,
         CTE.[Count], 
         ProductNames + N' , ' + ProductName, 
         [Rank]+1 
  From 
    CTE inner join Product 
      on CTE.ProductCategoryId = Product.ProductCategoryId 
      and CTE.ProductNames Not Like '%'+ProductName+'%' 
      and CTE.[Rank] < cte.[Count]
)
Select ProductCategoryId,
       Max(ProductNames) ProductNames,
       Max([Count]) [Count] 
From CTE 
Group by ProductCategoryId 
order by ProductCategoryId

1 个答案:

答案 0 :(得分:4)

我之前在递归CTE中的字符串类型上收到此错误。我只是通过将值转换为大字符串来修复它:

  Select ProductCategoryId,
         Count(*) as [Count], 
         cast(Max(ProductName) as nvarchar(max)) as ProductNames, 
         0 as [Rank] 
  From Product 
  Group By ProductCategoryId 

  Union ALL 

  Select CTE.ProductCategoryId,
         CTE.[Count], 
         cast(ProductNames + N' , ' + ProductName as nvarchar(max)), 
         [Rank]+1 
  From 
    CTE inner join Product 
      on CTE.ProductCategoryId = Product.ProductCategoryId 
      and CTE.ProductNames Not Like '%'+ProductName+'%' 
      and CTE.[Rank] < cte.[Count]