I\'m writing an export function, where I need to export contacts to Excel, and I\'ve run into a technical snag - or perhaps a gap in my SQL skills is closer to the truth. ;)
EDIT: Rewritten from table to scalar function based on devio's idea so if you like this post vote for his answer.
If CLR integration is not an option, you can accomplish this with a scalar function:
create function dbo.getRole(
@ContactId int)
returns varchar(8000)
as
begin
declare @Roles varchar(8000)
select
@Roles = case when @Roles is null then '' else @Roles + ', ' end + Role.Name
from Role
inner join ContactRole on Role.ID = ContactRole.RoleID
where ContactRole.ContactID = @ContactID
return @Roles
You can then call this function to calculate the comma-separated list for each contact:
SELECT c.id, c.name, dbo.getRole(ID) as Roles
FROM Contact