代码之家  ›  专栏  ›  技术社区  ›  Christoph Jonathan

在T-SQL中用单个空格替换重复的空格

  •  85
  • Christoph Jonathan  · 技术社区  · 16 年前

    我需要确保一个给定的字段在字符之间没有超过一个空格(我不关心所有的空格,只关心空格)。

    所以呢

    'single    spaces   only'
    

    需要变成

    'single spaces only'
    

    下面的方法不起作用

    select replace('single    spaces   only','  ',' ')
    

    'single  spaces  only'
    

    我更喜欢使用原生的T-SQL,而不是基于CLR的解决方案。

    思想?

    13 回复  |  直到 15 年前
        1
  •  352
  •   Neil Knight    8 年前

    更整洁:

    select string = replace(replace(replace(' select   single       spaces',' ','<>'),'><',''),'<>',' ')
    

    输出:

    选择单个空间

        2
  •  26
  •   Mutation Person    16 年前

    这将起作用:

    declare @test varchar(100)
    set @test = 'this   is  a    test'
    
    while charindex('  ',@test  ) > 0
    begin
       set @test = replace(@test, '  ', ' ')
    end
    
    select @test
    
        3
  •  18
  •   BradC    16 年前

    如果您知道一行中不会有超过一定数量的空格,则可以嵌套replace:

    replace(replace(replace(replace(myText,'  ',' '),'  ',' '),'  ',' '),'  ',' ')
    

    如果它可能要长得多,那么你必须做一些类似于内联函数的事情:

    CREATE FUNCTION strip_spaces(@str varchar(8000))
    RETURNS varchar(8000) AS
    BEGIN 
        WHILE CHARINDEX('  ', @str) > 0 
            SET @str = REPLACE(@str, '  ', ' ')
    
        RETURN @str
    END
    

    那就做吧

    SELECT dbo.strip_spaces(myText) FROM myTable
    
        4
  •  6
  •   JohnFx    16 年前

    CREATE FUNCTION stripDoubleSpaces(@prmSource varchar(max)) Returns varchar(max)
    AS 
    BEGIN
        WHILE (PATINDEX('%  %', @prmSource)>0)
         BEGIN
            SET @prmSource = replace(@prmSource  ,'  ',' ')
         END
    
        RETURN @prmSource
    END
    
    GO
    
    -- Unit test -- 
    PRINT dbo.stripDoubleSpaces('single    spaces   only')
    
    single spaces only
    
        5
  •  6
  •   HLGEM    15 年前
    update mytable
    set myfield = replace (myfield, '  ',  ' ')
    where charindex('  ', myfield) > 0 
    

    替换将在所有的双空格上工作,不需要放入多个替换。这是基于集合的解决方案。

        6
  •  6
  •   Community Mohan Dere    6 年前

    CREATE FUNCTION dbo.RemSpaceFromStr(@str VARCHAR(MAX)) RETURNS VARCHAR(MAX) AS
    BEGIN
      RETURN (CASE WHEN CHARINDEX('  ', @str) > 0 THEN
        dbo.RemSpaceFromStr(REPLACE(@str, '  ', ' ')) ELSE @str END);
    END
    

    例如:

    SELECT dbo.RemSpaceFromStr('some   string    with         many     spaces') AS NewStr
    

    退货:

    NewStr
    some string with many spaces
    

    或基于@agdk26或@Neil Knight所述方法的解决方案(但更安全)
    两个示例都返回上面的输出:

    SELECT REPLACE(REPLACE(REPLACE('some   string    with         many     spaces'
      , '  ', ' ' + CHAR(7)), CHAR(7) + ' ', ''), ' ' + CHAR(7), ' ') AS NewStr 
    --but it remove CHAR(7) (Bell) from string if exists...
    

    或

    SELECT REPLACE(REPLACE(REPLACE('some   string    with         many     spaces'
      , '  ', ' ' + CHAR(7) + CHAR(7)), CHAR(7) + CHAR(7) + ' ', ''), ' ' + CHAR(7) + CHAR(7), ' ') AS NewStr
    --but it remove CHAR(7) + CHAR(7) from string
    

    enter image description here

    注意事项:
    用于替换空格的Char/string不应该存在于字符串的开头或结尾,并且是独立的。

        7
  •  3
  •   Tomasz Jakub Rup    10 年前

    CREATE FUNCTION [dbo].[fnReplaceMultipleSpaces] (@StrVal AS VARCHAR(4000)) 
    RETURNS VARCHAR(4000) 
    AS 
    BEGIN
    
        SET @StrVal = Ltrim(@StrVal)
        SET @StrVal = Rtrim(@StrVal)
    
        SET @StrVal = REPLACE(@StrVal, '                ', ' ')  -- 16 spaces
        SET @StrVal = REPLACE(@StrVal, '        ', ' ')  -- 8 spaces
        SET @StrVal = REPLACE(@StrVal, '    ', ' ')  -- 4 spaces
        SET @StrVal = REPLACE(@StrVal, '  ', ' ')  -- 2 spaces
        SET @StrVal = REPLACE(@StrVal, '  ', ' ')  -- 2 spaces (for odd leftovers)
    
    RETURN @StrVal
    
    END
    
        8
  •  2
  •   user6097216 user6097216    10 年前

    方法#1

    下面是一个代码示例,用于替换字符串变量中的文本。

    DECLARE @testString AS VARCHAR(256) = ' Test        text   with  random*        spacing. Please normalize  this spacing!';
    SELECT REPLACE(REPLACE(REPLACE(@testString, ' ', '*^'), '^*', ''), '*^', ' ');
    

    执行时间测试#1:在这个替换方法的10次运行中,服务器回复的平均等待时间为1.7毫秒,总执行时间为4.6毫秒。

    方法#2

    第二种方法不如第一种方法优雅,但也能完成任务。此方法的工作原理是嵌套四个(或更多)replace语句,用一个空格替换两个空格。

    DECLARE @testString AS VARCHAR(256) = ' Test        text   with  random*        spacing. Please normalize  this spacing!';
    SELECT REPLACE(REPLACE(REPLACE(REPLACE(@testString,' ',' '),' ',' '),' ',' '),' ',' ')
    

    执行时间测试#1:在这个替换方法的十次运行中,服务器回复的平均等待时间是1.9毫秒,总执行时间是3.8毫秒。 执行时间测试2:服务器回复的平均等待时间为1.8毫秒,总执行时间为4.8毫秒。

    替换单词之间多余空格的第三种方法是使用简单循环。您可以在while循环中检查多余的空间,然后使用replace函数在循环的每次迭代中减少多余的空间。

    DECLARE @testString AS VARCHAR(256) = ' Test text with random* spacing. Please normalize this spacing!';
    WHILE CHARINDEX(' ',@testString) > 0
    SET @testString = REPLACE(@testString, ' ', ' ')
    SELECT @testString
    

    执行时间测试2:服务器回复的平均等待时间为1.9毫秒,总执行时间为2.8毫秒。

        9
  •  1
  •   Limey    11 年前

    在寻找答案时发现:

    SELECT REPLACE(
            REPLACE(
                 REPLACE(
                    LTRIM(RTRIM('1 2  3   4    5     6'))
                ,'  ',' '+CHAR(7))
            ,CHAR(7)+' ','')
        ,CHAR(7),'') AS CleanString
    where charindex('  ', '1 2  3   4    5     6') > 0
    

    完整答案(带解释)来自: http://techtipsbysatish.blogspot.com/2010/08/sql-server-replace-multiple-spaces-with.html

    再看,似乎只是选择了一个略有不同的答案版本。

        10
  •  1
  •   agdk26    10 年前

    declare @value varchar(max)
    declare @result varchar(max)
    set @value = 'alpha   beta gamma  delta       xyz'
    
    set @result = replace(replace(replace(replace(replace(replace(replace(
      @value,'a','ac'),'x','ab'),'  ',' x'),'x ',''),'x',''),'ab','x'),'ac','a')
    
    select @result -- 'alpha beta gamma delta xyz'
    
        11
  •  1
  •   Code    7 年前
     DECLARE @str varchar(150)
    SET @str='Hello    My   name  is Jiyaul   mustafa'
    Select REPLACE(REPLACE(REPLACE(@str,' ','{}'),'}{',''),'{}',' ')
    
        12
  •  0
  •   Eralper    7 年前

    我使用XML路径解决方案 replace multiple spaces into single space

    其思想是用XML标记替换空格 最后通过在两个字符串之间添加单个空格字符来连接这些字符串值

    下面是如何调用最终的UDF函数

    select dbo.ReplaceMultipleSpaces('   Sample   text  with  multiple  space     ')
    
        13
  •  0
  •   Matthys Du Toit    7 年前

    declare @s varchar(50)
    set @s = 'TEST         TEST'
    select REPLACE(REPLACE(REPLACE(@s,' ','[o][c]'),'[c][o]',''),'[o][c]',' ')
    
        14
  •  0
  •   Arulmouzhi    6 年前

    只是添加另一种方法-

    在SQL Server中用单个空间替换多个空间而不使用替换-

    DECLARE @TestTable AS TABLE(input VARCHAR(MAX));
    
    INSERT INTO @TestTable VALUES
    ('HAPPY         NEWYEAR     2020'),
    ('WELCOME       ALL     !');
    
    SELECT
        CAST('<r><![CDATA[' + input + ']]></r>' AS XML).value('(/r/text())[1] cast as xs:token?','VARCHAR(MAX)')
        AS Expected_Result
    FROM @TestTable;
    
    --OUTPUT
    /*
    Expected_Result
    HAPPY NEWYEAR 2020
    WELCOME ALL !
    */
    
        15
  •  0
  •   Jaimil Patel    6 年前

    请查找下面的代码

    select trim(string_agg(value,' ')) from STRING_SPLIT('  single    spaces   only  ',' ')
    where value<>' '
    

    这对我有用。。 希望这有帮助。。。

        16
  •  -1
  •   Ori Dar    9 年前

    你可以试试这个:

    select Regexp_Replace('single    spaces   only','( ){2,}', ' ') from dual;
    
        17
  •  -3
  •   Taryn Frank Pearson    12 年前
    update mytable
    set myfield = replace(myfield, '  ',  ' ')
    where myfield like '%  %'