我希望通过执行以下操作来选择列作为逗号分隔值:
select column1+','+column2+','+column3+','+coulmn4 from someTable
除非任何列保存空值,否则我必须跳过该列添加逗号 怎么做这个是SQL Server? [所有列都是varchar类型,因此不需要转换]
答案 0 :(得分:5)
Select
Case When Len(IsNull(Column1),'') > 0 Then Column1 + ',' Else '' End,
Case When Len(IsNull(Column2),'') > 0 Then Column2 + ',' Else '' End,
Case When Len(IsNull(Column3),'') > 0 Then Column3 + ',' Else '' End,
Case When Len(IsNull(Column4),'') > 0 Then Column4 + ',' Else '' End,
Case When Len(IsNull(ColumnN),'') > 0 Then ColumnN + ',' Else '' End
From
SomeTable
答案 1 :(得分:4)
试
测试表
create table #testCol (column1 varchar(10), column2 varchar(10),
column3 varchar(10), column4 varchar(10))
insert #testCol values('a', null,null,'b')
insert #testCol values(null,'a',null,'b' )
insert #testCol values(null,'a','Z','b' )
查询
select isnull(column1,'')+ case when column1 is null then '' else ',' end
+ isnull(column2,'')+ case when column2 is null then '' else ',' end
+ isnull(column3,'')+ case when column3 is null then '' else ',' end
+ isnull(column4,'')
from #testCol
输出
A,B
A,B
a,Z,b
答案 2 :(得分:0)
你可以导出到csv,然后删除所有双逗号吗?
答案 3 :(得分:0)
select isnull(column1 + ',', '') + isnull(column2 + ',', '') + isnull(column3 + ',', '') + isnull(coulmn4, '') from someTable