-3

I need to remove duplicate spaces in a string and leave only one, identical to function trim Excel. How to do this in sql?

  • 2
    Use `ltrim(rtrim(col))`. – Gordon Linoff Apr 11 '16 at 14:23
  • 3
    Possible duplicate of [Replace duplicate spaces with a single space in T-SQL](http://stackoverflow.com/questions/2455750/replace-duplicate-spaces-with-a-single-space-in-t-sql) – Siyual Apr 11 '16 at 14:23
  • Trim removes leading/trailing spaces. Not necessarily duplicated spaces. Do you want to trim a string or remove mid string duplicates? – David Rushton Apr 11 '16 at 15:01
  • try: `SELECT REPLACE(REPLACE(REPLACE('some string with many spaces' , ' ', ' ' + CHAR(7)), CHAR(7) + ' ', ''), CHAR(7), '') AS NewStr` – Adam Silenko Apr 11 '16 at 17:25

1 Answers1

0
Declare @spaces varchar(100) = 'String     With Spaces'

SELECT REPLACE(
          REPLACE(
            REPLACE(
                LTRIM(RTRIM(@spaces))
            ,'  ', ' ' + CHAR(100)) 
          ,CHAR(100) + ' ', '')
       ,CHAR(100), '') AS Result
Mike Deluca
  • 1,295
  • 2
  • 18
  • 41