如何使用 sql 服务器查询删除手机号码中第二次出现的 space

How to remove second occuring space in handphone number using sql server query

例如我的手机号码是123 456 789 我需要输出为123 456789。 如何实现?

应该这样做:

DECLARE @number AS NVARCHAR(12);
SELECT @number = '123 456 789';

SELECT STUFF(@number, CHARINDEX(' ', @number, CHARINDEX(' ', @number) + 1), 1, '')  AS REMOVED_SECOND_SPACE;
DECLARE @s VARCHAR(12) = '111 222 333'

SELECT SUBSTRING(@s, 0, LEN(@s) - CHARINDEX(' ', REVERSE(@s)) + 1)
     + SUBSTRING(@s, LEN(@s) - CHARINDEX(' ', REVERSE(@s)) + 2, CHARINDEX(' ', REVERSE(@s)));

这里的合乎逻辑的方法是使用 CHARINDEX and SUBSTRING, up to the first space, and after the first space, then REPLACE the string after the first space, then use CONCAT 将字符串分成两部分,然后将字符串重新组合在一起。例如

DECLARE @s VARCHAR(15) = '123 456 789';

SELECT  BeforeSpace = SUBSTRING(@s, 1, CHARINDEX(' ', @s)),
        AfterSpace = SUBSTRING(@s, CHARINDEX(' ', @s), LEN(@s)),
        ReplaceAfterSpace = REPLACE(SUBSTRING(@s, CHARINDEX(' ', @s), LEN(@s)), ' ', ''),
        Result = CONCAT(SUBSTRING(@s, 1, CHARINDEX(' ', @s)),
                        REPLACE(SUBSTRING(@s, CHARINDEX(' ', @s), LEN(@s)), ' ', ''));

不过,其实更简单,使用REPLACE and re-insert a space where the first one was originally using STUFF删除所有space:

DECLARE @s VARCHAR(15) = '123 456 789';

SELECT  STUFF(REPLACE(@s, ' ', ''), CHARINDEX(' ', @s), 0, ' ');

剩下要做的就是检查没有 space 的情况。完整示例:

DECLARE @T TABLE (s VARCHAR(15));
INSERT @T VALUES ('123 456 789'), ('123456789'), ('123456 789'), ('123 4 5 6 789');

SELECT  Original = s,
        Method1 = CASE WHEN CHARINDEX(' ', s) = 0 THEN s
                        ELSE CONCAT(SUBSTRING(s, 1, CHARINDEX(' ', s)), 
                                REPLACE(SUBSTRING(s, CHARINDEX(' ', s), LEN(s)), ' ', ''))
                    END,
        Method2 = CASE WHEN CHARINDEX(' ', s) = 0 THEN s
                        ELSE STUFF(REPLACE(s, ' ', ''), CHARINDEX(' ', S), 0, ' ')
                    END
FROM    @T;

输出

Original        Method1         Method2
-------------------------------------------
123 456 789     123 456789      123 456789
123456789       123456789       123456789
123456 789      123456 789      123456 789
123 4 5 6 789   123 456789      123 456789

N.B 我假设当您说要替换第二个 space 时,您想要替换所有 space首先。如果我的假设是错误的,并且它只是您想要替换的第二个 space 那么这将不起作用。

好吧,除了其他答案,我会 post 最简单的,基于假设,你想要三个数字后跟 space,然后是其余的:

declare @x1 varchar(15), @x2 varchar(15), @x3 varchar(15), @x4 varchar(15), @x5 varchar(15)
set @x1 = '123456789'
set @x2 = '123 456789'
set @x3 = '123 456 789'
set @x4 = '123456 789'
set @x5 = '1 2 3 4 5 6 7 8 9'

select stuff(replace(@x1, ' ', ''), 4, 0, ' ')
select stuff(replace(@x2, ' ', ''), 4, 0, ' ')
select stuff(replace(@x3, ' ', ''), 4, 0, ' ')
select stuff(replace(@x4, ' ', ''), 4, 0, ' ')
select stuff(replace(@x5, ' ', ''), 4, 0, ' ')

所有输出都相同:123 456789