使用SQL删除回车

时间:2015-08-12 14:35:53

标签: sql sql-server-2008 tsql

我有以下SQL将我的地址字段连接到ADDRESSLINE1

SELECT Isnull(ADDRESSLINE1 + Char(13)+Char(10), '')
       + Isnull(ADDRESSLINE2 + Char(13)+Char(10), '')
       + Isnull(ADDRESSLINE3, '') AS ADDRESSLINE1

它返回:

ADDRESSLINE1       
------------------ -----------------------------------
10 TEST ROAD



(1 row(s) affected)

如何修改我的代码,以便ADDRESSLINE2ADDRESSLINE3为空白''然后删除不必要的回车。

我希望:

ADDRESSLINE1       
------------------ -----------------------------------
10 TEST ROAD

(1 row(s) affected)

1 个答案:

答案 0 :(得分:1)

将CR + LF添加到每一行,然后使用REVERSE(STUFF(REVERSE()))方法删除最后两个字符。

SELECT REVERSE(STUFF(REVERSE(Isnull(ADDRESSLINE1 + Char(13)+Char(10), '')
       + Isnull(ADDRESSLINE2 + Char(13)+Char(10), '')
       + Isnull(ADDRESSLINE3 + Char(13)+Char(10), '')),1,2,'')) AS ADDRESSLINE1

如果您的字段中有空字符串,请尝试此操作:

SELECT REVERSE(STUFF(REVERSE(Isnull(NULLIF(ADDRESSLINE1,'') + Char(13)+Char(10), '')
       + Isnull(NULLIF(ADDRESSLINE2,'') + Char(13)+Char(10), '')
       + Isnull(NULLIF(ADDRESSLINE3,'') + Char(13)+Char(10), '')),1,2,'')) AS ADDRESSLINE1