4

Possible Duplicate:
Concat field value to string in SQL Server

What is the SQL Server equivalent of WM_CONCAT?

Community
  • 1
  • 1
RGO
  • 4,586
  • 3
  • 26
  • 40
  • 3
    http://stackoverflow.com/questions/1621747/concat-field-value-to-string-in-sql-server – Habib Sep 24 '12 at 05:55

1 Answers1

8

You don't have an equivalent function for that, but you can still simulate (make useof CROSS APPLY and FOR XML PATH('')). example,

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

will result

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

Using this query:

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

John Woo
  • 258,903
  • 69
  • 498
  • 492