-1

I have a string like this ' Hello <> world '. I am using below code to remove duplicate space from the string. But it removes <> from the string.

SELECT ' Hello  <>   world ' AS Name
INTO #Temp;

SELECT REPLACE(REPLACE(REPLACE(RTRIM(LTRIM(Name)), ' ', '<>'), '><', ''), '<>', ' ') AS CleanName
FROM #Temp;

Is there any alternative?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Jay Desai
  • 821
  • 3
  • 15
  • 42
  • @SRM : not a duplicate, the question you are referring removes ALL spaces, while the OP wants to retain non-duplicated spaces in the middle of the string – GMB Dec 18 '18 at 23:15

3 Answers3

2

Use this expression instead, that relies on non-printable ASCII characters :

SELECT REPLACE(REPLACE(REPLACE(RTRIM(LTRIM(Name)),' ','CHAR(17)CHAR(18)'),'CHAR(18)CHAR(17)',''),'CHAR(17)CHAR(18)',' ') AS CleanName
FROM #Temp;

Yields :

Hello <> world
GMB
  • 216,147
  • 25
  • 84
  • 135
1

Maybe this could help you:

declare @Name varchar(200)
select @Name = ' Hello  <>   world '
while charindex('  ',@Name)>0 select @Name=REPLACE(@Name,'  ',' ')
select @Name
Xabi
  • 465
  • 5
  • 8
0

The technique is solid, but if you want to keep <>, then you can use a rare text pattern

Example

SELECT ltrim(rtrim(replace(replace(replace(Name,' ','†‡'),'‡†',''),'†‡',' ')))
FROM #Temp;

Returns

Hello <> world

Note: the ltrim(rtrim(...)) is optional

John Cappelletti
  • 79,615
  • 7
  • 44
  • 66