用单个空格替换重复空白的SQL方法

cin*_*ndi 24 sql

有没有更优雅的方式这样做.我想用单个空白替换重复空白....

   declare @i int

    set @i=0
    while @i <= 20
    begin
        update myTable
        set myTextColumn = replace(myTextColumn, '  ', ' ')
        set @i=@i+1
    end
Run Code Online (Sandbox Code Playgroud)

(它的SQL Server 2000 - 但我更喜欢通用SQL)

Pau*_*aul 29

这有效:

UPDATE myTable
SET myTextColumn =
    REPLACE(
        REPLACE(
            REPLACE(myTextColumn
                ,'  ',' '+CHAR(1)) -- CHAR(1) is unlikely to appear
        ,CHAR(1)+' ','')
    ,CHAR(1),'')
WHERE myTextColumn LIKE '%  %'
Run Code Online (Sandbox Code Playgroud)

完全基于集合; 没有循环.

所以我们用不寻常的角色和空格替换任何两个空格.如果我们调用异常字符X,则5个空格变为:'XX',6个空格变为'XX X'.然后我们用空字符串替换'X'.因此,5个空格变为'',6个空格变为'X'.然后,如果有偶数个空格,我们删除任何剩余的'X',留下一个空格.


And*_*rew 28

这是一个简单的基于集合的方法,通过应用三个替换将多个空间折叠到一个空间中.

DECLARE @myTable TABLE (myTextColumn VARCHAR(50))

INSERT INTO @myTable VALUES ('0Space')
INSERT INTO @myTable VALUES (' 1 Spaces 1 Spaces. ')
INSERT INTO @myTable VALUES ('  2  Spaces  2  Spaces.  ')
INSERT INTO @myTable VALUES ('   3   Spaces  3   Spaces.   ')
INSERT INTO @myTable VALUES ('    4    Spaces  4    Spaces.    ')
INSERT INTO @myTable VALUES ('     5     Spaces  5     Spaces.     ')
INSERT INTO @myTable VALUES ('      6      Spaces  6      Spaces.      ')

select replace(
          replace(
             replace(
                LTrim(RTrim(myTextColumn)), ---Trim the field
             '  ',' |'),                    ---Mark double spaces
          '| ',''),                         ---Delete double spaces offset by 1
       '|','')                              ---Tidy up
       AS SingleSpaceTextColumn
 from @myTable
Run Code Online (Sandbox Code Playgroud)

您的Update语句现在可以基于以下设置:

 update @myTable
    set myTextColumn = replace(
                          replace(
                             replace(
                                LTrim(RTrim(myTextColumn)),
                             '  ',' |'),
                          '| ',''),
                       '|','')  
Run Code Online (Sandbox Code Playgroud)

使用适当的Where子句将Update限制为仅需要更新或可能具有双倍空格的行.

例:

where 1<=Patindex('%  %', myTextColumn)
Run Code Online (Sandbox Code Playgroud)

我找到了一个关于这个方法的外部写法:用一个替换多个空格


小智 6

select 
    string = replace(
                replace(
                    replace(' select   single       spaces',' ','<>')
                    ,'><','')
                ,'<>',' ')
Run Code Online (Sandbox Code Playgroud)

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