Question

I am currently trying to simulate the group_concat function in MySQL to MSSQL. I have followed code formats found in here and here. The problem is, when I try to execute the query, I get the message Ambiguous column name for my column RoleID. Here is my query:

select UserName, RoleID from tb_UserInRoles
cross apply(
    select RoleName from tb_Roles
    where tb_UserInRoles.RoleID = tb_Roles.RoleID
    for XML Path('')
) fxMerge (RoleID) group by UserName, RoleID

I'd like to know why this particular code format present the Ambiguous column name error message. I need to make this query work and understand it. Thanks in advance for the help.

I plan on using this in a many-to-many relationship table, wherein users of a system can have multiple roles, like this:

|  User  |   Role  |
|--------|---------|
| JamesP |  Maker  |
| JamesP | Approver|
| JamesP |  Admin  |

I want the result query to be like this:

|  User  |           Role           |
|--------|--------------------------|
| JamesP |  Maker, Approver, Admin  |
Was it helpful?

Solution

Try this:

SELECT UIR.UserName, MAX(STUFF(fxMerge.RoleID, 1, 1, '')) 
FROM tb_UserInRoles UIR
CROSS APPLY(
    SELECT ',' + RoleName 
    FROM tb_UserInRoles UIR1 
    INNER JOIN tb_Roles RM ON UIR1.RoleID = RM.RoleID
    WHERE UIR.UserName = UIR1.UserName 
    FOR XML PATH('')
) fxMerge (RoleID) 
GROUP BY UIR.UserName
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top