SQL Server相当于WM_CONCAT函数

时间:2012-09-24 05:53:46

标签: sql database oracle sql-server-2008 tsql

  

可能重复:
  Concat field value to string in SQL Server

与WM_CONCAT等效的SQL Server是什么?

1 个答案:

答案 0 :(得分:5)

您没有相应的功能,但您仍然可以模拟(使用CROSS APPLYFOR XML PATH(''))。例如,

USERID  ADDRESSLINE1
==========================
1       First Street
1       Second Street
2       32th Street
2       24th Street
2       25th Street

将导致

USERID  ADDRESSLIST
============================
1       First Street, Second Street
2       32th Street, 24th Street, 25th Street

使用此查询:

SELECT  a.UserID, 
        SUBSTRING(d.Addresses,1, LEN(d.Addresses) - 1) AddressList
FROM
        (
            SELECT DISTINCT UserID
            FROM tableName
        ) a
        CROSS APPLY
        (
            SELECT [AddressLine1] + ', ' 
            FROM tableName AS B 
            WHERE A.UserID = B.UserID 
            FOR XML PATH('')
        ) D (Addresses) 

SQLFiddle Demo