在SQL Server 2008中删除字符串中的所有空格的最佳方法是什么?

LTRIM(RTRIM(' a b '))将删除字符串右侧和左侧的所有空格,但我还需要删除中间的空格。


当前回答

这是去除字符串上的空格的技巧:

UPDATE
    tablename
SET
    columnname = replace(columnname, ' ', '');

其他回答

取代()函数:

REPLACE(field, ' ', '')

一个功能版本(udf),删除空格,cr, lf,制表符或可配置。

select Common.ufn_RemoveWhitespace(' 234   asdf   wefwef 3  x   ', default) as S

结果:234 asdfwefwef3x

alter function Common.RemoveWhitespace
(
    @pString nvarchar(max),
    @pWhitespaceCharsOpt nvarchar(max) = null -- default: tab, lf, cr, space 
)  
returns nvarchar(max) as
/*--------------------------------------------------------------------------------------------------
    Purpose:   Compress whitespace

    Example:  select Common.ufn_RemoveWhitespace(' 234   asdf   wefwef 3  x   ', default) as s 
              -- Result: 234asdfwefwef3x

    Modified    By          Description
    ----------  ----------- --------------------------------------------------------------------
    2018.07.24  crokusek    Initial Version 
  --------------------------------------------------------------------------------------------------*/ 
begin    
    declare 
        @maxLen bigint = 1073741823, -- (2^31 - 1) / 2 (https://stackoverflow.com/a/4270085/538763)
        @whitespaceChars nvarchar(30) = coalesce(
            @pWhitespaceCharsOpt, 
            char(9) + char(10) + char(13) + char(32));  -- tab, lf, cr, space

    declare
        @whitespacePattern nvarchar(30) = '%[' + @whitespaceChars + ']%',
        @nonWhitespacePattern nvarchar(30) = '%[^' + @whitespaceChars + ']%',
        @previousString nvarchar(max) = '';

    while (@pString != @previousString)
    begin
        set @previousString = @pString;

        declare
            @whiteIndex int = patindex(@whitespacePattern, @pString);

        if (@whiteIndex > 0)
        begin                   
            declare 
                @whitespaceLength int = nullif(patindex(@nonWhitespacePattern, substring(@pString, @whiteIndex, @maxLen)), 0) - 1;                

            set @pString = 
                substring(@pString, 1, @whiteIndex - 1) + 
                iif(@whiteSpaceLength > 0, substring(@pString, @whiteIndex + @whiteSpaceLength, @maxLen), '');
        end        
    end        
    return @pString;
end
go

从左到右删除字符串中的空格。要消除中间空间,请使用Replace。

您可以使用RTRIM()从右边删除空格,使用LTRIM()从左边删除空格,因此左右空格被删除如下:

SELECT * FROM table WHERE LTRIM(RTRIM(username)) = LTRIM(RTRIM("Bob alias baby"))

我会使用REPLACE

select REPLACE (' Hello , How Are You ?', ' ', '' )

取代

我今天遇到了这个问题,替换/修剪成功了,见下文。

update table_foo 
set column_bar  = REPLACE(LTRIM(RTRIM(column_bar)), '  ', '')

前后:

old-bad:  column_bar    |   New-fixed:   column_bar
       '  xyz  '        |                'xyz'   
       '  xyz  '        |                'xyz' 
       '  xyz  '        |                'xyz' 
       '  xyz  '        |                'xyz' 
       '  xyz  '        |                'xyz' 
       '  xyz  '        |                'xyz'