锚和递归查询“CTE”列“ColumnName”中的递归部分之间的类型不匹配

时间:2018-04-20 06:24:50

标签: sql sql-server tsql string-concatenation recursive-cte

尝试将多行的连接复制到一个字符串中 - > 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类型之间不匹配   锚和递归查询列“CodeList”中的递归部分   “CTE”。

我知道这是一个经常被问到的问题,但我无法从错误的地方得到。 经过测试,我发现当我在问号之间添加一段代码时就会出现这种情况。 它已被铸造,但它仍然给出错误

1 个答案:

答案 0 :(得分:0)

最后,我用另一个逻辑解决了这个问题:

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;