Concatenate Column

  • I have the following data. How do I concatenate the UserText Column to produce only 1 row for each UserID?

    UserID              UserText

    1                     ABC

    1                     DEF

    1                     GHI

    2                     ABC

    2                     DEF

    2                     GHI

     


    Kindest Regards,

  • IMO, this calls for a User-defined function:

    -- Create a testing table

    Create Table TestTable (ID int, TestStr varchar(20))

    GO

    Insert Into TestTable Values (1, 'ABC')

    Insert Into TestTable Values (1, 'DDD')

    Insert Into TestTable Values (1, 'ZZZ')

    Insert Into TestTable Values (2, 'NOX')

    Insert Into TestTable Values (2, 'IOU')

    Insert Into TestTable Values (2, 'S')

    GO

    -- Create the UDF.  This uses the Concatenation on select trick

    Create Function dbo.ufn_ConcatTestTable

     (@ID int)

    RETURNS varchar(256)

    AS

    BEGIN

       Declare @Work varchar(256)

       Set @Work = ''

       Select @Work = @Work + TestStr + ', '

       FROM TestTable

       WHERE [id] = @ID

       IF Len(@Work) > 0 Set @Work = Left(@Work, Len(@Work) - 1)

       Return @Work

    END

    GO

    -- And the test

    Select Test.ID, dbo.ufn_ConcatTestTable(Test.ID) As List

    From

     (Select TestTable.ID

     From TestTable

     Group By TestTable.ID) Test

    --- Results ---

    ID              List

    ----------- -----------------------------------------------------------

    1               ABC, DDD, ZZZ

    2               NOX, IOU, S

     

  • That works well. Thanks.


    Kindest Regards,

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply