1

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"
1

1 Answer 1

1

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;
Sign up to request clarification or add additional context in comments.

2 Comments

how can add a comma at the end of the string too ? like this "my image url , my image url2 ,"
@TarikHusin . . . for xml path returns the results as an XML string, which in this case is the string that you want.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.