Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
I have a table "EmployeeRoles" with columns "Employee_Id" and "Role".There is no Primary Key as individual Employee_IDs can have more than one Role. I'm trying to create a select which will result in two columns... one for Employee_ID and one for a concatenated string of roles.So, for example, if my EmployeeRoles table data contains:EmpA, Role1EmpA, Role2EmpB, Role1EmpC, Role3I would like to have a select that returnsEmpA, Role1|Role2EmpB, Role1Empc, Role3Now, I know how to do this if I want to concatenate records into a variable like:DELCARE @roles nvarchar(max)SET @roles = ''SELECT @roles = @roles + er.Role + '|' FROM EmployeeRoles erHowever, I need the concatenated string to be part of a select that returns the roles for each employee_id. Can anyone help? Thanks in advance!
Lamprey
Master Smack Fu Yak Hacker
4614 Posts
Posted - 2011-03-15 : 18:13:30
Here is one way:
DECLARE @T TABLE (Employee_Id VARCHAR(10), Role VARCHAR(10))INSERT @T VALUES ('EmpA', 'Role1'),('EmpA', 'Role2'),('EmpB', 'Role1'),('EmpC', 'Role3')SELECT Employee_Id,STUFF((SELECT '|' + Role FROM @T AS T1 WHERE T1.Employee_Id = T.Employee_Id ORDER BY T1.Role FOR XML PATH('')), 1, 1, '') AS RolesFROM @T AS TGROUP BY Employee_Id