0

How can I append records of two fields in single row.

Let's say, we have two columns in a table containing n number of records. I need to append each row having comma delimited in a single row.

Col1
Abs
Abd
Abf
Abg


Col2
10
15
20
0

Desired output

O/pcol
Abs:10 ;Abd:15 ;Abf:20 ;Abg:0

I hope this helps.

Andrea
  • 11,801
  • 17
  • 65
  • 72
Manish
  • 1
  • 3

1 Answers1

1

You can use an "accumulator" variable to concatenate all the values:

declare @testTable table (Col1 nvarchar(50),Col2 nvarchar(50))
declare @accumulator nvarchar(max)

insert into @testTable
          select 'Abs',10
union all select 'Abd',15
union all select 'Abf',20
union all select 'Abg',0

set @accumulator =''

select @accumulator = @accumulator + Col1 + ':' + Col2 + ' ;' from @testTable

select @accumulator

The output of this snippet should be:

Abs:10 ;Abd:15 ;Abf:20 ;Abg:0 ;

Andrea
  • 11,801
  • 17
  • 65
  • 72