锚和递归查询“CTE”列“ColumnName”中的递归部分之间的类型不匹配
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了锚和递归查询“CTE”列“ColumnName”中的递归部分之间的类型不匹配相关的知识,希望对你有一定的参考价值。
尝试将多行的连接复制到一个字符串中 - > https://www.red-gate.com/simple-talk/sql/t-sql-programming/concatenating-row-values-in-transact-sql/#Toc205129485
这是查询:
WITH CTE (id, CodeList, Code, Length)
AS (SELECT CAST(d.id AS NVARCHAR(MAX)) AS Id,
CAST('' AS NVARCHAR(MAX)) AS CodeList,
CAST('' AS NVARCHAR(MAX)) AS Code,
0 AS Length
FROM Letters d
INNER JOIN Cat c
ON c.ID = Cat_Sub
GROUP BY d.id
UNION ALL
SELECT CAST(dp.id AS NVARCHAR(MAX)) AS Id,
CAST(
CAST(CodeList AS NVARCHAR(MAX))
+ CASE
WHEN CAST(Length AS NVARCHAR(MAX)) = CAST('0' AS NVARCHAR(MAX)) THEN
CAST('' AS NVARCHAR(MAX))
ELSE
CAST(', ' AS NVARCHAR(MAX))
END
?????+ CAST(cp.Code AS NVARCHAR(MAX))??????
AS NVARCHAR(MAX)
) AS CodeList,
CAST(c.Code AS NVARCHAR(MAX)) AS Code,
c.Length + 1
FROM CTE c
INNER JOIN Letters dp
ON c.id= dp.id
INNER JOIN Cat cp
ON cp.ID = dp.id
WHERE cp.Code > c.Code
)
SELECT *
FROM CTE;
消息240,级别16,状态1,行1类型在锚和递归查询“CTE”的列“CodeList”中的递归部分之间不匹配。
我知道这是一个经常被问到的问题,但我无法从错误的地方得到。经过测试,我发现当我在问号之间添加一段代码时就会出现这种情况。它已被铸造但仍然出错
答案
最后,我用另一个逻辑解决了这个问题:
WITH Ranked ( CategoryId, rnk, ProductName )
AS ( SELECT CategoryId,
ROW_NUMBER() OVER( PARTITION BY CategoryId ORDER BY CategoryId ),
CAST( ProductName AS VARCHAR(8000) )
FROM Northwind..Products),
AnchorRanked ( CategoryId, rnk, ProductName )
AS ( SELECT CategoryId, rnk, ProductName
FROM Ranked
WHERE rnk = 1 ),
RecurRanked ( CategoryId, rnk, ProductName )
AS ( SELECT CategoryId, rnk, ProductName
FROM AnchorRanked
UNION ALL
SELECT Ranked.CategoryId, Ranked.rnk,
RecurRanked.ProductName + ', ' + Ranked.ProductName
FROM Ranked
INNER JOIN RecurRanked
ON Ranked.CategoryId = RecurRanked.CategoryId
AND Ranked.rnk = RecurRanked.rnk + 1 )
SELECT CategoryId, MAX( ProductName )
FROM RecurRanked
GROUP BY CategoryId;
以上是关于锚和递归查询“CTE”列“ColumnName”中的递归部分之间的类型不匹配的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Spring Data JPA 中使用 CTE 表达式 WITH 子句
sql server使用cte递归查询获取树形的父节点/子节点