Dynamically concatenate string

  • I have a below sample t-sql, i am trying to dynamically concatenate the rows, the number of rows can vary .  Any pointers would be helpful.

     

    drop table if exists #T1



    create table #T1
    (

    FileName char(400)
    )


    Insert into #T1
    select 'ABC'

    Insert into #T1
    Select 'DEF'

    select * from #T1

    -- Desired output: filename='ABC',filename='DEF'
  • This will concatenate the values as per the sample data

    SELECT STUFF((
    SELECT ',filename=''' + RTRIM(FileName) + ''''
    FROM #T1
    FOR XML PATH('')
    ), 1, 1, '')
  • Whatever method you're trying, you're probably running into problems because you've defined the [FileName] column as a CHAR(400).  For the value of "ABC", that means the row contains "ABC" followed by 397 spaces, which messes up concatenation attempts.  You just need to do an RTRIM on the [FileName] value to make it work... like this...

     SELECT DISTINCT
    DesiredOutput = STUFF(
    (
    SELECT ',filename='+RTRIM(t1.[FileName])
    FROM #T1 t1
    FOR XML PATH(''),TYPE
    ).value('(./text())[1]','VARCHAR(MAX)')
    ,1,1,'')
    FROM #T1 t2
    ;

    Either that or define the [FileName] column as a VARCHAR(400) instead of a CHAR(400).

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)

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

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