如何在SQL Server中使用CTE连接字符串?

时间:2014-08-20 23:33:59

标签: sql-server common-table-expression

使用CTE或公用表表达式,如何跨多行连接字符串。

1 个答案:

答案 0 :(得分:0)

  1. 按州分列县(NumberedCounties)
  2. 选择每个州的第一个县(JoinedCounties,RowNumber = 1)
  3. 选择每个州的第二个县(JoinedCounties,RowNumber = RowNumber + 1)
  4. 获取最大行号(WithMax)
  5. 按最大行数过滤
  6. 确保不超过递归限制。
  7.    WITH    NumberedCounties(RowNumber, County, State)
                  AS (SELECT    ROW_NUMBER() OVER (PARTITION BY C.State ORDER BY c.County),
                                c.County,
                                c.State
                      FROM      Static.County C
                     ),
                JoinedCounties(RowNumber, Counties, State)
                  AS (SELECT    RowNumber,
                                CONVERT(VARCHAR(4000), County),
                                State
                      FROM      NumberedCounties
                      WHERE     RowNumber = 1
                      UNION ALL
                      SELECT    C.RowNumber,
                                CONVERT(VARCHAR(4000), R.Counties + ', '
                                + C.County),
                                C.State
                      FROM      JoinedCounties R
                                INNER JOIN NumberedCounties C ON R.State = C.State
                                                                 AND C.RowNumber = (R.RowNumber
                                                                      + 1)
                     ),
                WithMax(Counties, State, RowNumber, MaxRowNumber)
                  AS (SELECT    Counties,
                                State,
                                RowNumber,
                                MAX(RowNumber) OVER (PARTITION BY State) AS MaxRowNumber
                      FROM      JoinedCounties
                     )
            SELECT  Counties,
                    State
            FROM    WithMax
            WHERE   RowNumber = MaxRowNumber
        OPTION  (MAXRECURSION 500);
    

    注意:如果你有一些非常重要的记录,那么与在应用程序中连接记录相比,这将会非常慢。