2017-02-01 60 views
0

如何在单行中追加两个字段的记录。添加两列记录

比方说,我们在包含n个记录的表中有两列。我需要在单行中添加以逗号分隔的每行。

Col1 
Abs 
Abd 
Abf 
Abg 


Col2 
10 
15 
20 
0 

所需的输出

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

我希望这有助于。

+1

样本数据和期望的结果将有所帮助 –

+1

请发布样本数据和预期输出。哦,嘿@约翰 – GurV

+0

这是你想要的吗? SELECT FIELD1 +','+ FIELD2 FROM YOURTABLE – NicoRiff

回答

1

可以使用一个 “累加器” 变量来连接所有的值:

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 

此代码段的输出应为:

ABS:10;阿卜杜勒:15; ABF:20 ; Abg:0;