2017-02-21 175 views
1

我有表包含地址1,地址2,地址3等...其中值可以爲空或空。與分隔符連接多個字段

我正在通過將這些字段連接成一個完整的地址。

Select Column1, Column2, ISNULL(Address1,'') + ', ' + ISNULL(Address2,'')+ ', ' + ISNULL(Address3,'') As FullAddress 
from TableName 

問題是如果address1爲null,但它仍附加我想要刪除的','。所以落得像「 address2value」

有沒有更好的做這個

回答

1

這是否做你心目中的方式?

Select Column1, 
     Column2, 
     ISNULL(Address1+',','') + ISNULL(Address2+',','')+ISNULL(Address3,'') As FullAddress 
from TableName 

結果:

enter image description here

+0

是的,但如果Address3爲空,它將在地址末尾留下',' – mrTester

+1

您可以使用以下鏈接生成ascii藝術表https://senseful.github.io/web-tools/text-table/ –

+0

很好,謝謝分享 – WilliamD

2

如果你不想尾隨或領先的逗號,你可以這樣做:

Select Column1, Column2, 
     STUFF(COALESCE(', ' + Address1, '') + COALESCE(', ' + Address2, '') + COALESCE(', ' + Address3, ''), 
      1, 2, '') As FullAddress 
from TableName; 
0

如果任何地址1或1地址或地址3包含Null ,它不會添加分隔符

SELECT Column1, Column2, CONCAT_WS(',',IFNULL(Address1,NULL),IFNULL(Address2,NULL),IFNULL(Address3,NULL)) AS FullAddress 
FROM TableName; 
+0

SQL Server ....................... –