0

试图将多行连接复制到一个字符串中--> https://www.red-gate.com/simple-talk/sql/t-sql-programming/concatenating-row-values-in-transact-sql/#目录205129485

这是查询:

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”列中的锚点和递归部分之间不匹配。

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

4

1 回答 1

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;
于 2018-04-20T12:17:52.210 回答