MySQL : how to remove double or more spaces from a string?

前端 未结 11 1284
南方客
南方客 2020-12-03 08:12

I couldn\'t find this question for MySQL so here it is:

I need to trim all double or more spaces in a string to 1 single space.

For example: \"The  

11条回答
  •  自闭症患者
    2020-12-03 08:23

    This is slightly general solution: from

    http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=56195&whichpage=1

    create table t (s sysname)
    insert into t select 'The   Quick  Brown    Fox'
    -- convert tabs to spaces
    update  t set s = replace(s, '  ',' ')
    where   charindex(' ', s) > 0
    
    -- now do the work.
    while 1=1
    begin
        update t
        set     s = substring(s, 1, charindex('  ', s, 1)-1) + ' ' + ltrim(substring(s,charindex('  ', s, 1), 8000))
        where   charindex('  ', s, 1) > 0
    
        if @@rowcount = 0
            break
    end
    
    select  s
    from    t
    

提交回复
热议问题