Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
SQL Replace multiple spaces with one
CREATE TABLE #ExtraSpaces ( MyVal VARCHAR(8000))
--Insert some value to test
INSERT INTO #ExtraSpaces
SELECT 'This is my message. '
UNION ALL
SELECT 'This message contains tabs and extra spaces'
-- Lets remove extra spaces and tabs
WHILE 1 = 1
BEGIN
UPDATE #ExtraSpaces
SET MyVal = REPLACE(
SUBSTRING(MyVal, 1,
CHARINDEX(' ', MyVal, 1) - 1) + ' '
+ LTRIM(
SUBSTRING(MyVal,
CHARINDEX(' ', MyVal, 1), 8000)),' ',' ')
WHERE CHARINDEX(' ', MyVal, 1) > 0
IF @@rowcount = 0
BREAK
END
--Lets see the updated result
SELECT MyVal FROM #ExtraSpaces
--drop temp table when not required
DROP TABLE #ExtraSpaces
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment