2017-09-06 32 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 
相關問題