Concatenate a selected column in a single query?

前端 未结 6 698
别跟我提以往
别跟我提以往 2020-12-21 21:47

I know you can do this, because I\'ve seen it done once before, but I forget where and up until now I haven\'t need to do it.

I have a table called Employees, and it

相关标签:
6条回答
  • 2020-12-21 22:19

    Use coalesce. Something like this:

    DECLARE @Names varchar(1000)
    SELECT @Names = COALESCE(@Names + ', ', '') + Name
    FROM Employees
    
    0 讨论(0)
  • 2020-12-21 22:21

    this isn't perfect, but it'll get you most of the way there

    declare @count int
    declare @i int
    declare @string nvarchar(max)
    declare @name nvarchar(100)
    
    declare @Employees (EmpName nvarchar(100), ID int identity(1,1)
    
    insert into @Employees (EmpName)
    select FirstName + ' ' + LastName
    from Employees
    
    
    select @count=count(*) from @Employees
    set @i=1
    set @string=''
    
    
    while (@i<=@count)
    begin
    
        select @name = EmpName from @Employees where ID=@i
    
        set @string = @string + ',' + @name
    
        set @i=@i+1
    end
    
    0 讨论(0)
  • 2020-12-21 22:26

    Maybe this can help. This question has been asked before. How to create a SQL Server function to "join" multiple rows from a subquery into a single delimited field?

    0 讨论(0)
  • 2020-12-21 22:28

    you can write a UDF to do that

    CREATE FUNCTION [dbo].[fnc_GetEmpList](
    @CompId numeric
    ) RETURNS nvarchar(1000)
    BEGIN
    
    declare @str nvarchar(1000)
    set @str =''
    
    select  @str = @str + ',' + FirstName + ' ' + LastName from Employees
    
    
    --remove the last comma
    if(@str<>'')
        set @str = right(@str,len(@str)-1)
    
    return @str
    
    
    END
    
    0 讨论(0)
  • 2020-12-21 22:30

    If you are using MySQL, they have a great function called GROUP_CONCAT that does just that. http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat

    0 讨论(0)
  • 2020-12-21 22:34

    This is the most efficient method I've found. It requires SQL Server, but it sounds like that's what you're using.

    select stuff((
        select ', ' + fName + ' ' + lName
        from Employees
        order by lName, fName /* Optional */
        for xml path('')
    ), 1, 2, '');
    

    The idea is that you can take advantage of the ability to use an empty tag name with for xml path('') to get string concatenation across rows. The stuff(...,1,2,'') just removes the leading comma.

    This is REALLY fast.

    0 讨论(0)
提交回复
热议问题