Microsoft SQL Server 2005 Best Practices

How to remove multiple spaces from a string?

 

Execute the following script in Query Editor to create the extra space removal function:

USE AdventureWorks;

CREATE FUNCTION fnRemoveMultipleSpaces(@InputString varchar(1024))
RETURNS varchar(1024)
AS
BEGIN

WHILE CHARINDEX(' ', @InputString) > 0
SET @InputString = REPLACE(@InputString, ' ', ' ') -- replace 2 spaces with 1 space

RETURN @InputString
END

-- SELECT dbo.fnRemoveMultipleSpaces ('The fox ran in the forest!')



 

The Best SQL Server 2005 Training in the World
 
 
SQLUSA.com Home Page