我正在构建一些视图以允许从另一个数据库导入一次数据。源表有零长度字符串(我将NULL
转换为NULLIF
)但该地址导致我出现问题。
示例源表;
IF OBJECT_ID('tempdb..#OriginalDataTable') IS NOT NULL DROP TABLE #OriginalDataTable
GO
CREATE TABLE #OriginalDataTable (RowID int, Address1 varchar(20), Address2 varchar(20), Address3 varchar(20), City varchar(10), State varchar(10))
INSERT INTO #OriginalDataTable (RowID, Address1, Address2, Address3, City, State)
VALUES
(1, '1 Wall Street','Downtown','','New York','NY')
,(2, '2 Floor Street','Uptown','','New York','NY')
,(3, '','','','','')
,(4, '3 Ceiling Street','','','New York','NY')
目前我倾向于每排一个CASE,但它看起来效率不高。任何人都可以为此提出更好的选择吗?
SELECT
Address1 + ', ' + Address2 + ', ' + Address3 + ', ' + City + ', ' + State [Easy_But_Wrong]
,NULLIF(Address1 +
CASE WHEN Address2 = '' THEN '' ELSE ', ' + Address2 END +
CASE WHEN Address3 = '' THEN '' ELSE ', ' + Address3 END +
CASE WHEN City = '' THEN '' ELSE ', ' + City END +
CASE WHEN State = '' THEN '' ELSE ', ' + State END ,'') [Using_CASE]
FROM #OriginalDataTable
必须将其构建到视图中,以便将一些方法放在窗口之外。
这是我当前的输出,我希望它看起来像右边的数据(注意第一列中的逗号。
Easy_But_Wrong Using_CASE
1 Wall Street, Downtown, , New York, NY 1 Wall Street, Downtown, New York, NY
2 Floor Street, Uptown, , New York, NY 2 Floor Street, Uptown, New York, NY
, , , , NULL
3 Ceiling Street, , , New York, NY 3 Ceiling Street, New York, NY
答案 0 :(得分:1)
这可能是this question的副本。
我已将此方法与NULLIF
结合使用以获得所需的输出;
SELECT
Stuff(
Coalesce(',' + NULLIF(Address1,''),'')
+ Coalesce(',' + NULLIF(Address2,''),'')
+ Coalesce(',' + NULLIF(Address3,''),'')
+ Coalesce(',' + NULLIF(City,''),'')
+ Coalesce(',' + NULLIF(State,''),'')
, 1, 1, '') [New_Address]
FROM #OriginalDataTable
结果;
New_Address
1 Wall Street,Downtown,New York,NY
2 Floor Street,Uptown,New York,NY
NULL
3 Ceiling Street,New York,NY