如何将列值转换为用别名分隔的逗号

时间:2017-01-14 06:45:17

标签: sql-server sql-server-2008

如何将列值转换为逗号分隔和别名,以便在动态查询中使用此输出? MyTable表有两列DayNo& CR_Date包含数据:

Day1    01/01/2000
Day2    01/02/2002
Day3    05/01/2003
Day4    01/01/1999
Day5    08/01/1998
Day6    01/19/2010
Day7    01/01/2000
Day8    01/01/2011
Day9    12/05/2000
Day10   01/01/2017

我的尝试:

declare @AllRowsInOneRow nvarchar (2000)
set @AllRowsInOneRow = ''

select @AllRowsInOneRow = 
case when @AllRowsInOneRow = ''
then CR_Date
else @AllRowsInOneRow + coalesce(''' as '+Day_No+',''' + CR_Date, '')
end
from MyTable

select @AllRowsInOneRow = 'select ''' + @AllRowsInOneRow + ''''

select @AllRowsInOneRow 

输出:

select '01/01/2000' as Day2,'01/02/2002' as Day3,'05/01/2003' as Day4,
'01/01/1999' as Day5,'08/01/1998' as Day6,'01/19/2010' as Day7,
'01/01/2000' as Day8,'01/01/2011' as Day9,'12/05/2000' as Day10, '01/01/2017'

期望的输出:

select '01/01/2000' as Day1,'01/02/2002' as Day2,'05/01/2003' as Day3,
'01/01/1999' as Day4,'08/01/1998' as Day5,'01/19/2010' as Day6,
'01/01/2000' as Day7,'01/01/2011' as Day8,'12/05/2000' as Day9,
'01/01/2017' as Day10

DDL:

Create table MyTable (Day_No varchar(5), CR_Date varchar(20))
go
insert into MyTable values ( 'Day1' , '01/01/2000')
insert into MyTable values ( 'Day2' , '01/02/2002')
insert into MyTable values ( 'Day3' , '05/01/2003')
insert into MyTable values ( 'Day4' , '01/01/1999')
insert into MyTable values ( 'Day5' , '08/01/1998')
insert into MyTable values ( 'Day6' , '01/19/2010')
insert into MyTable values ( 'Day7' , '01/01/2000')
insert into MyTable values ( 'Day8' , '01/01/2011')
insert into MyTable values ( 'Day9' , '12/05/2000')
insert into MyTable values ( 'Day10' , '01/01/2017')

1 个答案:

答案 0 :(得分:1)

试试这个会给你想要的输出。

pictureBox1->Refresh();

输出: -

declare @tmp varchar(250)           
SET @tmp = ''
select @tmp = @tmp + ''''+  CR_Date + '''' + ' as '  +Day_No + ', '      from MyTable

select  + 'select ' +  SUBSTRING(@tmp, 0, LEN(@tmp))