sql - 递归查询列中的 anchor 和递归部分之间的类型不匹配

标签 sql sql-server tsql

给定一个类别@categoryId,查询应递归导航到最顶层的 super 类别,这已完成。

现在我还想生成一个字符串,该字符串将是过程中所有 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".

感谢您的帮助

最佳答案

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

关于sql - 递归查询列中的 anchor 和递归部分之间的类型不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18110730/

相关文章:

.net - 通过ClickOnce升级SQL实例

java - 使用 mysql 更新时出错

sql-server - 如何仅根据行号将单列表变成多列?

c# - EF 代码优先 : Add row to table with a non-identity primary key

sql - 使用旋转将行转换为列

sql-server - SQL Server 中的分页

sql-server - 使用 #temp 表时未检测到无效列

mysql - 我知道 PIVOT 命令可以转换数据集,这是正确的方法吗?

sql - PK 顺序索引的填充因子

sql - 如何在sql中搜索以特定字母开头然后有数字的字符串?