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

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


当前回答

一个功能版本(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

其他回答

为了使以上所有的答案完整,在StackOverflow上有关于如何处理所有空白字符的额外帖子(请参阅https://en.wikipedia.org/wiki/Whitespace_character获取这些字符的完整列表):

TSQL 2008使用LTrim(RTrim和仍然有空间的数据 如何从SQL server中的列中删除非间断空格? 在没有UDF和CLR的T-SQL中,从字符串中修剪所有空白字符的好方法是什么?

简单地替换它;

SELECT REPLACE(fld_or_variable, ' ', '')

编辑: 澄清一下;它是一个全局替换,不需要trim()或担心char或varchar的多个空格:

create table #t (
    c char(8),
    v varchar(8))

insert #t (c, v) values 
    ('a a'    , 'a a'    ),
    ('a a  '  , 'a a  '  ),
    ('  a a'  , '  a a'  ),
    ('  a a  ', '  a a  ')

select
    '"' + c + '"' [IN], '"' + replace(c, ' ', '') + '"' [OUT]
from #t  
union all select
    '"' + v + '"', '"' + replace(v, ' ', '') + '"'
from #t 

结果

IN             OUT
===================
"a a     "     "aa"
"a a     "     "aa"
"  a a   "     "aa"
"  a a   "     "aa"
"a a"          "aa"
"a a  "        "aa"
"  a a"        "aa"
"  a a  "      "aa"

如果是对表的更新,则必须多次运行此更新,直到影响到0行为止。

update tableName
set colName = REPLACE(LTRIM(RTRIM(colName)), '  ', ' ')
where colName like '%  %'

如果你想从字符串中删除空格,-和另一个文本,那么使用以下命令:

假设您的表格中有一个手机号码,如“718-378-4957”或 ' 7183784957',你想要替换并获得手机号码,然后使用下面的文本。

select replace(replace(replace(replace(MobileNo,'-',''),'(',''),')',''),' ','') from EmployeeContactNumber

结果:——7183784957

我知道最初的问题是关于简单地替换空格,但如果你需要替换所有空白,你可以使用TRANSLATE函数(自Sql Server 2019以来)将给定的字符列表转换为更容易替换的内容。然后用REPLACE函数包装它。

这样可以避免重复调用:

DECLARE @Whitespace CHAR(4) = CHAR(0) + CHAR(9) + CHAR(13) + CHAR(10);
SELECT REPLACE(
    TRANSLATE(' TEST    ', @Whitespace, '    '),
    ' ', '');