将MSSQL中的所有非数字字符替换为空字符串


Replace all non numeric characters in MSSQL with an empty string

我当前的MSSQL表有一个"phone"列,它是一个varchar。不幸的是,数据库中已经存在的电话号码不是标准格式。例如:888-8888 -8888 OR 888/888/8888 OR (888)8888888 OR 8888888888

我想获得所有与88888888相等的行,即它应该与888-888-8888,(888)888888等匹配。

我已经尝试使用REPLACE(),但有某些行,其中条目有其他字母字符,如"e","ex","ext"等。所以我想替换所有非数字字符。

使用MSSQL查询获得"匹配"行的最佳方法是什么?

你可以试试这个函数(MS SQL Server):

CREATE FUNCTION uf_RemoveNotNumbers (@str varchar(max))
RETURNS varchar(max)
AS
BEGIN
    WHILE @str LIKE '%[^0-9]%' 
    SET @str=replace(@str, substring(@str, patindex('%[^0-9]%',@str),1),'');
    RETURN @str
END
GO

DECLARE @str varchar(max);
SET @str = 'q56--89+9*67qweresr';
select dbo.uf_RemoveNotNumbers (@str)

使用MySQL的简单版本:

SELECT * FROM `phones` WHERE `phone` LIKE '%8%8%8%8%8%8%8%8%8%8%'
使用PHP:

// Get all your table rows into $rows using SELECT ..
foreach ($rows as $row) {
    $row['phone'] = preg_replace('/'D/', '', $row['phone'];
    // Save the row using UPDATE ..
}

正则表达式'D匹配任何非数字字符。详见php.net/preg_replace

如果你只想找到匹配"8888888888"的行,那么你可以使用:

if (preg_match('/'D*8'D*8'D*8'D*8'D*8'D*8'D*8'D*8'D*8'D*8'D*/', $row['phone'])) {
    ..
}

可以简化/抽象为:

$match = '8888888888';
if (preg_match('/' . preg_replace('/('d)/', ''D*$1', $match) . ''D*/', $row['phone'])) {
    ..
}

为什么不写一个php脚本来帮你做呢?

交货。获取所有行-> replace -> update

这里是可能在MSSQL上工作的查询。

create FUNCTION dbo.Only_Numbers
(
    @string VARCHAR(8000)
)
RETURNS VARCHAR(8000)
AS
BEGIN
DECLARE @IncorrectCharLoc SMALLINT
SET @IncorrectCharLoc = PATINDEX('%[^0-9]%', @string)
WHILE @IncorrectCharLoc > 0
BEGIN
    SET @string = STUFF(@string, @IncorrectCharLoc, 1, '')
    SET @IncorrectCharLoc = PATINDEX('%[^0-9]%', @string)
    END
    SET @string = @string
Return  @string 
END
GO
select dbo.Only_Numbers('888*88-88/2')

你可以试试下面的代码:

$query="select * from tablename";
$result=mysql_query($query);
while($row=mysql_fetch_array($result))
{
    $str = preg_replace('['D]', '', $row['phone']);
}