Ishwor
Ishwor

Reputation: 68

Replace all non numeric characters in MSSQL with an empty string

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?

Upvotes: 2

Views: 3299

Answers (5)

Igor Borisenko
Igor Borisenko

Reputation: 3866

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)

Upvotes: 2

John Ken
John Ken

Reputation: 962

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']);
}

Upvotes: 0

B'man Sresta
B'man Sresta

Reputation: 1

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')

Upvotes: 0

Rusty Fausak
Rusty Fausak

Reputation: 7525

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'])) {
    ..
}

Upvotes: 1

Meisam Mulla
Meisam Mulla

Reputation: 1871

Why not write a php script that would do it for you?

ex. get all rows -> replace -> update

Upvotes: 0

Related Questions