2013-06-20 41 views

回答

5

對於SQL 2000,我能想到的唯一方法就是使用REPLACE函數。

declare @SearchTerm bigint 

Set @SearchTerm = 5553442524 

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

的問題,這將是它不會迎合領先1

一種更好的方式將包裹這一切的邏輯in to a function

例如

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 

要調用的函數,你會使用它,像這樣:

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

或者在WHERE子句中使用它:

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

顯然這裏的最好的事情是清潔提取存儲在列中的數據並限制插入的任何進一步的「不良」數據。儘管根據我的經驗,說起來容易做起來難。

+0

我希望能夠清理入站數據,但正如您所說,由於數據來自上百個網站並且需要在每個實例中進行重新調整,因此如您所說的那樣更容易。 –

+0

@TonyMancini您可以在表中添加一個觸發器,以便在將數據保存到數據庫之前通過該函數傳遞數據。這會爲你清理數據。但是,您必須確保您的功能考慮了防止失敗的所有可能性。在執行生產之前,我還會對性能做一些測試。 – codingbadger

+0

我試圖運行查詢時似乎遇到錯誤; 'SELECT * FROM crm_main AS E,dbo.fn_FormatTelephoneNumber('5553442524')AS EID WHERE E.phone = EID.phone' - 我得到無效的對象名'dbo.fn_FormatTelephoneNumber'。 –

相關問題