Remove Multiple Spaces

I have a need to replace multiple space with a single space in varchar during a SQL statement.
 
On the web there were many solutions, but these two seemed to be the more simple ones.
 

DECLARE

@strValue VARCHAR(MAX)

SET @strValue = sf    ds     fds f fds fd sf    ds    

 
While

CharIndex(‘  ‘, @strValue)>0

    Select

@strValue = Replace(@strValue, ‘  ‘, ‘ ‘)

 

–********************************

DECLARE

@strValue VARCHAR(MAX)

SET

@strValue = ‘     sf ds fds f ds       fds         fd sf ds ‘

SELECT

LTRIM(REPLACE(REPLACE(REPLACE(@strValue,‘  ‘, ‘ ‘), ‘  ‘, ‘ ‘), ‘  ‘, ‘ ‘))

 
Resources:
 
Removing unwanted spaces within a string …
 
Squeeze Function

Leave a Reply

Your email address will not be published. Required fields are marked *