代码改变世界

替换字符串中连续空格为一个空格的方法(SQL)

2009-11-17 12:21  清海扬波  阅读(1056)  评论(0编辑  收藏  举报
DECLARE @Demo TABLE(OriginalString VARCHAR(8000))
 
INSERT INTO @Demo (OriginalString)
 
SELECT '  This      has multiple   unknown                 spaces in        it.   ' UNION ALL
 
SELECT 'So                     does                      this!' UNION ALL
 
SELECT 'As                                does                        this' UNION ALL
 
SELECT 'This, that, and the other  thing.' UNION ALL
 
SELECT 'This needs no repair.'

--===== Reduce each group of multiple spaces to a single space
     -- for a whole table without functions, loops, or other
     -- forms of slow RBAR.  In the following example, CHAR(7)
     -- is the "unlikely" character that "X" was used for in 
     -- the explanation.
 SELECT REPLACE(
            
REPLACE(
                
REPLACE(
                    
LTRIM(RTRIM(OriginalString))
                ,
'  ',' '+CHAR(7))  --Changes 2 spaces to the OX model
            ,CHAR(7)+' ','')        --Changes the XO model to nothing
        ,CHAR(7),''AS CleanString --Changes the remaining X's to nothing
   FROM @Demo
  
WHERE CHARINDEX('  ',OriginalString) > 0
一般方法都是用循环,但是这个不是,关键是有新意,这个是转贴,原出处链接在此