Tarik Husin
Tarik Husin

Reputation: 307

SQL concatenate strings in single value

I have two tables, users_tbl and images tbl.

Every user can have more than one image.

I'm trying to select all the users and concatenate the user image in a single row

Example :

Users tbl

user_id    user_name
--------------------
 1          david
 2          tarik

images tbl

image_id   user_id   image_url 
-------------------------------
1            1      "image 12312 url"
2            1      "image 123 url"
3            1      "image 313 url"
4            1      "image 212 url"
5            2      "my image url"
5            2      "my image url2"

I need a select statement that returns the following result:

user_id   image_url 
----------------------------------------------------------------------
    1     "image 12312 url ,image 123 url,image 313 url,image 212 url"
    2     "my image url , my image url2"

Upvotes: 1

Views: 66

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269445

In SQL Server 2012, you would use for xml path:

select u.*,
       stuff( (select ', ' + i.image_url
               from images i
               where i.user_id = u.user_id
               for xml path ('')
              ), 1, 2, ''
            ) as image_urls
from users u;

EDIT:

If you want the comma at the end, leave out the stuff() and use:

select u.*,
       (select i.image_url + ', '
        from images i
        where i.user_id = u.user_id
        for xml path ('')
       ) as image_urls
from users u;

Upvotes: 1

Related Questions