2017-09-06 35 views
-1

我在一个表4列称为RelationRecord如何在我的情况下使用SQL Server连接字符串?

RelationRecord

Parent Child1 Child2 Child3 
------------------------------------ 
111  111  null  111 
222  null  null  null 
null  333  null  null 
null  null  null  444 
555  555  555  555 

我想通过逗号像下面

期待输出

111,111 
222 
333 
444 
555,555,555,555 
做连击和独立

我尝试使用caseisnull但它不起作用。当我使用case时,查询会变得很多。有其他解决方案吗?

回答

3

下面是一个方法:

select stuff((coalesce(',' + child1, '') + 
       coalesce(',' + child2, '') + 
       coalesce(',' + child3, '') + 
       coalesce(',' + child4, '') 
      ), 1, 1, '' 
      ) 

stuff()用于去除前导逗号(如果有的话)在结果列。

+0

'1,1'是什么? –

+0

@mohamedfaiz。 。 。参数'stuff()'。 –

+0

它的工作。请给我'coalesce'的定义也请.. 8分钟后我会接受答案。谢谢 –

0

我可不是为此感到自豪,但不会把戏

select 
isnull(cast(Parent as varchar(19)),'') + 
case 
    when Parent is null then '' 
    when Child1 is null then '' 
    else ',' end + 
isnull(cast(Child1 as varchar(59)),'') + 
case 
    when Child1 is null then '' 
    when Child2 is null then '' 
    else ',' end + 
isnull(cast(Child2 as varchar(59)),'') + 
case 
    when Child2 is null then '' 
    when Child3 is null then '' 
    else ',' end + 
isnull(cast(Child3 as varchar(59)),'')from Table_1 
1

如果2012+,另一个选择是concat()

Select NewValue = IsNull(stuff(concat(','+Child1 
             ,','+Child2 
             ,','+Child3 
             ),1,1,''),Parent) 
From YourTable 

返回

NewValue 
111,111 
222   -- Notice Parent is displayed 
333 
444 
555,555,555 
相关问题