IncreMan
IncreMan

Reputation: 356

SQL Server regex and if else in where clause

This is my code:

$db = new COM("ADODB.Connection");
$dsn = "DRIVER={SQL Server}; SERVER={$server}; UID={$usr}; PWD={$pwd}; DATABASE={$dbname}";
$db->Open($dsn);
$sql = "SELECT o.CardCode, o.CardName, o.VatIDNum, o.AddID, o.Cellular, o.E_Mail, c.Address
            FROM ocrd o INNER JOIN crd1 c ON o.CardCode = c.CardCode
            WHERE o.Cellular = '$phone1' o.CardName LIKE N'%$lname%'";
$result = $db->execute($sql);

In the databese the o.Cellular column includes phone numbers that could be formatted with dashes/spaces/+ sign/braces so when I am checking WHERE o.Cellular = '$phone1' I need to reformat o.Cellular to only digits (the $phone1 already only digits).

The second problem is that if o.Cellular not equals $phone1, I want to check o.CardName LIKE N'%$lname%'.

So the current part of code doesn't works as I need.

Any help please...

Upvotes: 3

Views: 314

Answers (2)

IncreMan
IncreMan

Reputation: 356

My own final solution:

$phone1 = "0123456789"; /* tests 0123456789 */
$phone1 = preg_replace("/\D+/", "", $phone); /* Leave digits only */
$phone1_wildcard = "%".implode("%",str_split($phone1))."%"; /* converts 0123456789 to %0%1%2%3%4%5%6%7%8%9% in order to catch any mistyping in mssql */

Upvotes: 0

S3S
S3S

Reputation: 25112

REGEX is extremely limited in SQL Server. Here's an example to replace the following characters in your phone number: + ( ) - \s

SELECT 
    o.CardCode, 
    o.CardName, 
    o.VatIDNum, 
    o.AddID, 
    o.Cellular, 
    o.E_Mail, 
    c.Address
FROM 
    ocrd o 
    INNER JOIN 
        crd1 c ON 
        o.CardCode = c.CardCode
WHERE 
    replace(replace(replace(replace(replace(o.Cellular,'-',''),' ',''),'(',''),')',''),'+','') = '$phone1' 
    or o.CardName LIKE N'%$lname%'

--test example you can run to see the results of the code

declare @Cellular varchar(16) = '+1 (156) 555-7899'
select replace(replace(replace(replace(replace(@Cellular,'-',''),' ',''),'(',''),')',''),'+','')

--returns 1156555789

Upvotes: 1

Related Questions