问题
My current MSSQL table has a "phone" column which is a varchar. Unfortunately, the phone numbers that are already in the database are not in standard format. For example, 888-888-8888 OR 888/888/8888 OR (888)8888888 OR 8888888888.
I want to get all the rows that are equivalent to 88888888, i.e it should match with 888-888-8888, (888)888888 etc.
I have tried using REPLACE() but there are certain rows where entries have other alphabetic characters like "e", "ex", "ext", etc. So I would like to replace all non-numeric characters.
What would be the best way to get the "matching" rows using MSSQL query?
回答1:
A simple version using MySQL:
SELECT * FROM `phones` WHERE `phone` LIKE '%8%8%8%8%8%8%8%8%8%8%'
Using 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 ..
}
The regular expression \D
matches any non-numeric character. See php.net/preg_replace for more information.
If you just want to find a row that matches "8888888888", then you could use:
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'])) {
..
}
Which could simplify/abstract to:
$match = '8888888888';
if (preg_match('/' . preg_replace('/(\d)/', '\D*$1', $match) . '\D*/', $row['phone'])) {
..
}
回答2:
You can try this function (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)
回答3:
Why not write a php script that would do it for you?
ex. get all rows -> replace -> update
回答4:
heres the query that might work on 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')
回答5:
You can try this code:
$query="select * from tablename";
$result=mysql_query($query);
while($row=mysql_fetch_array($result))
{
$str = preg_replace('[\D]', '', $row['phone']);
}
来源:https://stackoverflow.com/questions/7523872/replace-all-non-numeric-characters-in-mssql-with-an-empty-string