SQL method to replace repeating blanks with single blanks

前端 未结 15 2004
既然无缘
既然无缘 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:35

    This works:

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

    Entirely set-based; no loops.

    So we replace any two spaces with an unusual character and a space. If we call the unusual character X, 5 spaces become: ' X X ' and 6 spaces become ' X X X'. Then we replace 'X ' with the empty string. So 5 spaces become ' ' and 6 spaces become ' X'. Then, in case there was an even number of spaces, we remove any remaining 'X's, leaving a single space.

提交回复
热议问题