SQL 服务器正则表达式和 if else 在 where 子句中

SQL Server regex and if else in where clause

这是我的代码:

$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);

在数据库中,o.Cellular 列包括 phone 可以用 dashes/spaces/+ sign/braces 格式化的数字,所以当我检查 WHERE o.Cellular = '$phone1' 我需要将 o.Cellular 重新格式化为只有数字($phone1 已经只有数字)。

第二个问题是,如果o.Cellular不等于$phone1,我想检查o.CardName LIKE N'%$lname%'

所以代码的当前部分不符合我的需要。

任何帮助请...

REGEX 在 SQL 服务器中非常有限。下面是替换 phone 号码中的以下字符的示例:+ ( ) - \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

我自己的最终解决方案:

$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 */