2017-09-14 119 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