2017-09-14 111 views
2

在SQL Server 2014中刪除字符串中所有空格的最佳方法是什麼?刪除所有空格並在SQL中將多行聯合爲單行

我的字符串是:

Maximize your productivity for building engaging, 

beautiful web mapping applications 

試圖刪除輸入和字符串和字之間1個空間之間標籤空間。結果應該是這樣的:

Maximize your productivity for building engaging, beautiful web mapping applications 
+0

這是可重複使用的用戶定義的函數的良好候選者。 –

+0

查看更新的答案。我刪除了32.沒有必要 –

回答

1

如果對UDF開放,則以下操作將刪除所有控制字符並重復空格。

重複空間的去除啓發(OK被盜)從戈登回答幾個月前。

Declare @S varchar(max) = 'Maximize your productivity for building engaging, 

beautiful web mapping applications' 


Select [dbo].[svf-Str-Strip-Control](@S) 

返回

Maximize your productivity for building engaging, beautiful web mapping applications 

的UDF如果有意

CREATE FUNCTION [dbo].[svf-Str-Strip-Control](@S varchar(max)) 
Returns varchar(max) 
Begin 
    Select @S=Replace(@S,char(n),' ') 
    From (values (1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12),(13),(14),(15),(16),(17),(18),(19),(20),(21),(22),(23),(24),(25),(26),(27),(28),(29),(30),(31)) N(n) 

    Return LTrim(RTrim(Replace(Replace(Replace(@S,' ','><'),'<>',''),'><',' '))) 
End 
--Select [dbo].[svf-Str-Strip-Control]('Michael  '+char(13)+char(10)+'LastName') --Returns: Michael LastName 
+0

刪除值(32)...不需要/冗餘。 –

4

您可以使用replace(),但它是一個有點棘手:

select replace(replace(replace(replace(replace(col, ' ', '<>' 
              ), ' 
', '<>' 
            ), ' ', '<>' -- tab goes here 
          ), '><', '' 
         ), '<>', ' ' 
       ) 
from t; 

的想法是,一個空間被替換爲<>,則所有>< s的去掉只留下一。例如:

a b c  -- original data with three spaces and one space 
a<><><>b<>c -- after replacing spaces with <> 
a<>b<>c  -- after removing >< 
a b c  -- after replacing <> with a space 
+0

它適用於例如X輸入y字符串,但對於X輸入Y輸入Z不起作用 – Zr2271