2014-05-12 41 views
0

我想連接地址到表中的單個字段。連接地址刪除額外的逗號

Create table temp(ID int, Address1 varchar(100),Address2 varchar(100),Address3 varchar(100),City varchar(100), State varchar(100)) 
Insert into temp(1,'2 Main St','','','Allentown','PA') 
Insert into temp(2,'4 Bee St','PO Box 5067','','Bethlehem','PA') 
Insert into temp(3,'Building Two','Suite 208, 707 Alexander Road,','Pembroke Park','Easton','PA') 

我想創建一個顯示ID,地址作爲一個字段的視圖。即

2 Main St, Allentown,PA 
4 Bee St,PO Box 5067,Bethlehem,PA 
Building Two,Suite 208, 707 Alexander Road,Pembroke Park,Easton,PA 

Create VIEW [dbo].[vwtemp] 
AS 
SELECT ID, 
       isnull(Address1,NULL) AS "Address1", 
       isnull(Address2,NULL) AS "Address2", 
       isnull(Address3,NULL) AS "Address3", 
       isnull(City,NULL) AS "City", 
       isnull(State,NULL) AS "State",  
Stuff( 
    Coalesce(', ' + [Address1], '') 
    + Coalesce(', ' + [Address2],'') 
    + Coalesce(', ' + [Address3], '') 
    + Coalesce(', ' + [City], '') 
    + Coalesce(', ' + [State], '') 
) from temp 

上面的查詢插入額外逗號當ID 1,因爲地址3 & 2都爲空; ID = 2地址3爲空;

有任何建議。

由於 ř

回答

1

USE CASE語句而然後連接串CASE WHEN(地址2 IS NULL) '' ELSE( '' +地址2)END