SQL服务器替换可变数量的内部空格并替换为一个空格

时间:2013-11-18 22:16:30

标签: sql-server replace whitespace

我一直在寻找一种方法来在SQL查询中用一个空格替换字符串之间的所有空格。我发现很多对REPLACE的引用都很好,除了要替换的字符串必须准确。

我该如何改变

Bob     Jones to Bob Jones
Jim Jones to remain the same
Jeff         Jones to Jeff Jones

感谢任何帮助

2 个答案:

答案 0 :(得分:2)

DECLARE @String1 VARCHAR(1000) = 'Jeff         Jones to Jeff       Jones'
DECLARE @String2 VARCHAR(1000) = 'Bob     Jones to   Bob        Jones'

SELECT REPLACE(REPLACE(REPLACE(@String1,'  ',' '+CHAR(1)) ,CHAR(1)+' ',''),CHAR(1),'') AS Col

SELECT REPLACE(REPLACE(REPLACE(@String2,'  ',' '+CHAR(1)) ,CHAR(1)+' ',''),CHAR(1),'') AS Col

<强> RESULT

Col
Jeff Jones to Jeff Jones

Col
Bob Jones to Bob Jones

用户定义的功能

CREATE FUNCTION udf_ReplaceWhiteSpace(@String NVARCHAR(MAX))
RETURNS NVARCHAR(MAX)
AS
BEGIN
   DECLARE @RtnString NVARCHAR(MAX);

    SET @RtnString = REPLACE(REPLACE(REPLACE(@String,'  ',' '+CHAR(1)) ,CHAR(1)+' ',''),CHAR(1),'');

  RETURN @RtnString;
END

UDF测试

DECLARE @String VARCHAR(1000) = 'Jeff         Jones    to  Jones till       the       end'


SELECT dbo.udf_ReplaceWhiteSpace(@String) 

返回结果

Jeff Jones to Jones till the end

答案 1 :(得分:0)

有几种方法可以实现这一目标,您选择实施哪种方法主要取决于每种方法的性能。

此处详细介绍了所有方法:More Recursion–Removing Multiple SpacesDavid Howard

这是第一种使用递归的方法。我已更新示例代码以满足您的要求。

方法1 - 代码(功能):

CREATE FUNCTION dbo.RemoveMultipleSpaces (@str NVARCHAR(MAX))
    RETURNS NVARCHAR(MAX)
AS
BEGIN
    IF CHARINDEX('  ', @str) = 0
        RETURN @str;

    RETURN dbo.RemoveMultipleSpaces(REPLACE(@str, '  ', ' '));
END
GO

方法1示例:

DECLARE @s VARCHAR(MAX) = 'Bob     Jones';
DECLARE @s1 VARCHAR(MAX) = 'Jim Jones';
DECLARE @s2 VARCHAR(MAX) = 'Jeff         Jones';
SELECT @s as BeforeString, dbo.RemoveMultipleSpaces(@s) AS AfterString
UNION
SELECT @s1 as BeforeString, dbo.RemoveMultipleSpaces(@s1) AS AfterString
UNION
SELECT @s2 as BeforeString, dbo.RemoveMultipleSpaces(@s2) AS AfterString

方法1结果:

BeforeString              AfterString

Bob     Jones             Bob Jones
Jim Jones                 Jim Jones
Jeff         Jones        Jeff Jones