SQL method to replace repeating blanks with single blanks

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.

Leave a Comment