MSSQL: Remove extra spaces from a string.

Posted December 21st, 2012


Removes extra spaces from a string in SQL Server.

CREATE FUNCTION [dbo].[RemoveSpaces] (@Str VARCHAR(MAX))
RETURNS VARCHAR(MAX)
AS
BEGIN
        SET @str = REPLACE(@str,' ','{}')
        SET @str = REPLACE(@str,'}{','')
        SET @str = REPLACE(@str,'{}',' ')
        RETURN @str
END