4

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  |
JamesP
  • 195
  • 1
  • 3
  • 17

1 Answers1

6

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
Saharsh Shah
  • 28,687
  • 8
  • 48
  • 83
  • @JamesP Check my updated answer. It will resolve your problem. I had joined on the `USERNAME` column because I don't know the table structure. So you have to join on `USERID` column if you have. Change in query is WHERE `UIR.UserId = UIR1.UserId` instead of `UIR.UserName = UIR1.UserName` – Saharsh Shah Dec 16 '13 at 06:08
  • it works brilliantly now :) If you don't mind, I'd like to know which does what in the code, like, why did you use MAX and STUFF, why use INNER JOIN etc. – JamesP Dec 16 '13 at 06:19
  • @JamesP Subquery returns all the role name for particular user so I had to join both tables. the subquery returns `,Maker,Approver,Admin` for JampesP user. So I need ro remove first comman. So I have use STUFF function to implement this – Saharsh Shah Dec 16 '13 at 06:29
  • @JamesP Inner query not subquery. – Saharsh Shah Dec 16 '13 at 07:24