Here is a very efficient solution for removing multiple spaces from a string. I mean replacing multiple spaces between words in a string with a single space, without using a loop. The technique is very simple, I will just run a small script to show how it works.
DECLARE @str AS VARCHAR(50) SET @str = 'Lets jot some code' PRINT @str SET @str = REPLACE(@str,' ','{}') PRINT @str SET @str = REPLACE(@str,'}{','') PRINT @str SET @str = REPLACE(@str,'{}',' ') PRINT @str
And here is the output.
Lets jot some code Lets{}{}{}jot{}some{}{}code Lets{}jot{}some{}code Lets jot some code
Below is a function based on this technique.
CREATE FUNCTION RemoveSpaces ( -- ============================================= -- Author: Amit Singh -- Description: Remove extra spaces from string -- Usage: SELECT dbo.RemoveSpaces('Code Jotter') -- ============================================= @str AS VARCHAR(MAX) ) RETURNS VARCHAR(MAX) AS BEGIN RETURN REPLACE(REPLACE(REPLACE(@str,' ','{}'),'}{',''),'{}',' ') END GO
Wow! what an idea ! What a concept ! Beautiful .. Amazing
Brilliant, love it, thanks for sharing
Absolutely brilliant stuff!!
Lovely ! Superb
Ooooooooooo So Nice.
A kick yourself moment (but ok I probably wouldn’t have thought of that)
Great stuff Amit. Very cool lateral thinking !
Most helpful, thank you. This could be done outside of SQL with a regex match and replace, but that didn’t work with a vanilla SQL 2008 R2 instance. Your approach works great.
Regular Expression (regex) reference:
replace [ +] (one or more space characters)
with [ ] (one space character)
In an Oracle database, you can use regular expressions (even in SQL), the function would be:
REGEXP_REPLACE (‘Lets jot some code’, ‘() {2,}’, ‘ ‘)
Your RemoveSpaces function runs 3 times over the String the REGEXP_REPLACE only one time (but with a much more complex algorithm) so I cannot say what is faster.
Dear Sir, this is modafreakin’ brilliant. Cheers!
Wow!!! Amazing concept….Thank u
It is wonderful solution.