TSQL Comma Separation

前端 未结 7 1916
夕颜
夕颜 2020-12-10 20:12

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. ;)

7条回答
  •  长情又很酷
    2020-12-10 20:58

    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
    

提交回复
热议问题