SQL method to replace repeating blanks with single blanks

前端 未结 15 1929
既然无缘
既然无缘 2020-12-01 17:52

Is there a more elegant way of doing this. I want to replace repeating blanks with single blanks....

   declare @i int

    set @i=0
    while @i <= 20
           


        
相关标签:
15条回答
  • 2020-12-01 18:42

    Step through the characters one by one, and maintain a record of the previous character. If the current character is a space, and the last character is a space, stuff it.

    CREATE FUNCTION [dbo].[fnRemoveExtraSpaces]  (@Number AS varchar(1000))
    Returns Varchar(1000)
    As
    Begin
    Declare @n int  -- Length of counter
    Declare @old char(1)
    
    Set @n = 1
    --Begin Loop of field value
    While @n <=Len (@Number)
        BEGIN
         If Substring(@Number, @n, 1) = ' ' AND @old = ' '
          BEGIN
            Select @Number = Stuff( @Number , @n , 1 , '' )
          END
         Else
          BEGIN
           SET @old = Substring(@Number, @n, 1)
           Set @n = @n + 1
          END
        END
    Return @number
    END
    GO
    
    
    select [dbo].[fnRemoveExtraSpaces]('xxx     xxx     xxx    xxx')
    
    0 讨论(0)
  • 2020-12-01 18:42
    Update myTable set myTextColumn = replace(myTextColumn, '  ', ' ');
    

    The above query will remove all the double blank spaces with single blank space

    But this would work only once.

    0 讨论(0)
  • 2020-12-01 18:44

    Here is a Simplest solution :)

        update myTable
        set myTextColumn = replace(replace(replace(LTrim(RTrim(myTextColumn )),' ','<>'),'><',''),'<>',' ')
    
    0 讨论(0)
  • 2020-12-01 18:45
    WHILE
     (SELECT count(myIDcolumn) 
      from myTable where myTextColumn like '%  %') > 0
    BEGIN
      UPDATE myTable 
      SET myTextColumn = REPLACE(myTextColumn ,'  ',' ')
    END
    
    0 讨论(0)
  • 2020-12-01 18:48

    Try this:

    UPDATE Ships
    SET name = REPLACE(REPLACE(REPLACE(name, '  ', ' ' + CHAR(1)), CHAR(1) + ' ', ''), CHAR(1), '')
    WHERE name LIKE '%  %'
    
    0 讨论(0)
  • 2020-12-01 18:49
    select 
        string = replace(
                    replace(
                        replace(' select   single       spaces',' ','<>')
                        ,'><','')
                    ,'<>',' ')
    

    Replace duplicate spaces with a single space in T-SQL

    0 讨论(0)
提交回复
热议问题