Remove all spaces and combine multiple lines to single line in SQL

对着背影说爱祢 提交于 2020-01-04 05:41:26

问题


What is the best way to remove all spaces from a string in SQL Server 2014?

My string is:

Maximize your productivity for building engaging,

 beautiful web mapping applications

Trying to remove enter and tab spaces between string and 1 space between words. Result should be like:

Maximize your productivity for building engaging, beautiful web mapping applications

回答1:


If open to a UDF, the following will remove all control characters and repeating spaces.

The removal of the repeating spaces was inspired (OK stolen) from Gordon's answer a few months ago.

Example

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

 beautiful web mapping applications'


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

Returns

Maximize your productivity for building engaging, beautiful web mapping applications

The UDF if Interested

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



回答2:


You can use replace(), but it is a bit tricky:

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

The idea is that a space is replaced with <>, then all ><s are removed leaving only one. For instance:

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


来源:https://stackoverflow.com/questions/46225232/remove-all-spaces-and-combine-multiple-lines-to-single-line-in-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!