0

Using the PHP SQLSRV driver to connect to SQL Server 2000, is there a way I could match all of these rows using this piece of data: 5553442524?

555-344-2524
(555) 344-2524
555.344.2524
1-555-344-2524

I imagine this would be done through a specific query probably using a stored procedure?

Thank you.

1 Answer 1

5

For SQL 2000 the only way I can think of would be using the REPLACE function.

declare @SearchTerm bigint

Set @SearchTerm = 5553442524

Select * From dbo.Table 
Where Replace(Replace(Replace(Replace(Col1,'-',''), '(',''),')',''),'.','')
= @SearchTerm

The problem with this would be it wouldn't cater for the leading 1.

A better way would be wrap all this logic in to a function.

e.g.

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

To call the function you would use it like so:

Select *,
      dbo.fn_FormatTelephoneNumber(YourColumnName) as [FormattedTelephoneNumber]
From dbo.YourTable

Or to use it in a WHERE clause:

Select *
From dbo.YourTable
Where dbo.fn_FormatTelephoneNumber(YourColumnName) = 5553442524

Obviously the best thing here would be to clean up the data that is stored in the columns and restrict any further "bad" data from being inserted. Although in my experience that is easier said than done.

5
  • I'd like to be able to clean the data coming inbound, but as you said, easier said then done as the data is coming from over a hundred websites and would need to be readjusted in every instance.
    – Tony M
    Jun 20, 2013 at 15:27
  • @TonyMancini You could add a trigger to the table to pass the data through the function before saving it to the database. That would clean the data for you. However, you would have to ensure that your function accounted for all possibilities to prevent a failure. I would also do some testing regarding performance before implementing in production. Jun 20, 2013 at 15:33
  • I seem to be running into an error while trying to run the query; SELECT * FROM crm_main AS E, dbo.fn_FormatTelephoneNumber('5553442524') AS EID WHERE E.phone = EID.phone - I'm getting Invalid object name 'dbo.fn_FormatTelephoneNumber'.
    – Tony M
    Jun 20, 2013 at 15:35
  • Put the function call in your WHERE criteria, it's not returning a table object to be joined to.
    – Hart CO
    Jun 20, 2013 at 15:37
  • 1
    @TonyMancini See my edits on how to call the function in your queries. Jun 20, 2013 at 15:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.