August 28, 2019 at 2:20 am
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'
August 28, 2019 at 4:28 am
This will concatenate the values as per the sample data
SELECT STUFF((
SELECT ',filename=''' + RTRIM(FileName) + ''''
FROM #T1
FOR XML PATH('')
), 1, 1, '')
August 28, 2019 at 5:19 am
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
Change is inevitable... Change for the better is not.
Viewing 3 posts - 1 through 2 (of 2 total)
You must be logged in to reply to this topic. Login to reply