Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Excess Middle Spaces in Name - SQL

I've got a data-set of people's names but the problem is I imagine when some people were typing in their names they hit the spacebar a few times too many b/c now we have this:

enter image description here

Notice how in the name column there're some names like John_Doe, John__Doe, John____Doe, etc. What would be the best way to ensure that whenever there's a _ between words, be it 1,2,3, etc. it's removed/trimmed to only 1 space so all of these records would become John_Doe.

Thoughts?

like image 876
Joshua Avatar asked Aug 05 '13 19:08

Joshua


People also ask

How do I replace multiple spaces in single space in SQL?

DECLARE @Demo TABLE(OriginalString VARCHAR(8000)) INSERT INTO @Demo (OriginalString) SELECT ' This has multiple unknown spaces in it. ' UNION ALL SELECT 'So does this! ' UNION ALL SELECT 'As does this' UNION ALL SELECT 'This, that, and the other thing. ' UNION ALL SELECT 'This needs no repair.

What is trailing spaces in SQL?

When the right side of a LIKE predicate expression features a value with a trailing space, SQL Server does not pad the two values to the same length before the comparison occurs.

How do you trim a column in SQL?

SQL Server does not support for Trim() function. But you can use LTRIM() to remove leading spaces and RTRIM() to remove trailing spaces. can use it as LTRIM(RTRIM(ColumnName)) to remove both.


1 Answers

This should do the trick

DECLARE @string varchar(100)
SET @string = 'John   Doe'

SELECT string = REPLACE(REPLACE(REPLACE(@string,' ','<>'),'><',''),'<>',' ')

Replace duplicate spaces with a single space in T-SQL

like image 109
HKImpact Avatar answered Sep 28 '22 08:09

HKImpact