使用SQL Server,有没有办法使用5553442524查询(555)344-2524?

Ton*_*y M 0 php sql sql-server-2000

使用PHP SQLSRV驱动程序连接到SQL Server 2000,有没有办法可以使用这段数据匹配所有这些行:5553442524

555-344-2524
(555) 344-2524
555.344.2524
1-555-344-2524
Run Code Online (Sandbox Code Playgroud)

我想这可能是通过一个特定的查询可能使用存储过程完成的?

谢谢.

cod*_*ger 5

对于SQL 2000,我能想到的唯一方法就是使用该REPLACE函数.

declare @SearchTerm bigint

Set @SearchTerm = 5553442524

Select * From dbo.Table 
Where Replace(Replace(Replace(Replace(Col1,'-',''), '(',''),')',''),'.','')
= @SearchTerm
Run Code Online (Sandbox Code Playgroud)

这个问题就是它不能满足领先1.

更好的方法是将所有这些逻辑包装到函数中.

例如

Create Function dbo.fn_FormatTelephoneNumber(@input varchar(100))
returns bigint
as begin


declare @temp bigint

Set @temp = Replace(Replace(Replace(Replace(@input ,'-',''), '(',''),')',''),'.','')

If Len(@temp) = 11
begin
Set @temp = Right(@temp, 10)
end

return @temp

End
Run Code Online (Sandbox Code Playgroud)

要调用该函数,您将使用它,如下所示:

Select *,
      dbo.fn_FormatTelephoneNumber(YourColumnName) as [FormattedTelephoneNumber]
From dbo.YourTable
Run Code Online (Sandbox Code Playgroud)

或者在WHERE子句中使用它:

Select *
From dbo.YourTable
Where dbo.fn_FormatTelephoneNumber(YourColumnName) = 5553442524
Run Code Online (Sandbox Code Playgroud)

显然,这里最好的事情是清理存储在列中的数据并限制插入任何进一步的"坏"数据.虽然根据我的经验说起来容易做起来难.