SQL help! Joining multiple rows

Associate
Joined
6 Jan 2006
Posts
1,024
Location
Midlands
I have three tables
users
usersrole
roles

A user can have one to many roles (reason for usersrole table)

I want to write an sql which will return a row for each user and all the roles it belongs to in a comma separated format.
i.e.

Code:
USER       USERROLE
Bob        Member, Admin
Dave       Member

How do i do that?
 
SQL is designed to do set operations, what you want is not a set operation, as such you will need to use a cursor.

Cursors are bad..mmmkay?

If you're using .net look into LINQ (only avaliable in .net 3.5)

edit, or do it in code.

I.e. return a DataTable or similar in the form

user1 role1
user1 role2
user2 role1
user3 role2
user3 role3

etc

then loop through and build up your data how you want.
 
Last edited:
a UDF, something along the lines of:


DECLARE @roles VARCHAR(128)

SELECT
@roles = COALESCE(@roles + ', ', '') + userrole.role
FROM
userrole
WHERE
userrole.user = 'bob'

RETURN @roles
 
a UDF, something along the lines of:


DECLARE @roles VARCHAR(128)

SELECT
@roles = COALESCE(@roles + ', ', '') + userrole.role
FROM
userrole
WHERE
userrole.user = 'bob'

RETURN @roles

I dont see how it actually works but ill give it ago.
thanks for the help
 
Back
Top Bottom