SQL Server搜索时使用忽略空格

时间:2017-03-22 17:06:43

标签: sql sql-server database tsql sql-like

我在数据库中有一个phone列,并且记录右侧包含不需要的空格。我试图使用修剪和替换,但它没有返回正确的结果。

如果我使用

phone like '%2581254%'

它返回

 customerid
 -----------
 33470
 33472
 33473
 33474

但我只需要在开头使用百分号或外卡,我只想匹配左侧。

所以,如果我像这样使用它

 phone like '%2581254'

我什么都没得到,因为右边的空间!

所以我尝试使用trim和replace,我只得到一个结果

LTRIM(RTRIM(phone)) LIKE '%2581254'

返回

 customerid
 -----------
 33474

请注意,这四个ID具有相同的电话号码!

表格数据

customerid    phone
-------------------------------------
33470         96506217601532388254
33472         96506217601532388254
33473         96506217601532388254
33474         96506217601532388254  
33475         966508307940                                                                                                             

我为测试提议添加了许多数字

php函数占用最后7位并进行比较。

例如

01532388254 will be 2581254

我希望搜索其电话号码中包含此7位数字的所有用户 2581254

我无法弄清楚问题出在哪里!

它应该返回4个ID而不是1个id

1 个答案:

答案 0 :(得分:7)

根据示例数据,我怀疑您的数据中有控制字符。例如char(13),char(10)

要确认这一点,请运行以下

Select customerid,phone
 From  YourTable
 Where CharIndex(CHAR(0),[phone])+CharIndex(CHAR(1),[phone])+CharIndex(CHAR(2),[phone])+CharIndex(CHAR(3),[phone])
      +CharIndex(CHAR(4),[phone])+CharIndex(CHAR(5),[phone])+CharIndex(CHAR(6),[phone])+CharIndex(CHAR(7),[phone])
      +CharIndex(CHAR(8),[phone])+CharIndex(CHAR(9),[phone])+CharIndex(CHAR(10),[phone])+CharIndex(CHAR(11),[phone])
      +CharIndex(CHAR(12),[phone])+CharIndex(CHAR(13),[phone])+CharIndex(CHAR(14),[phone])+CharIndex(CHAR(15),[phone])
      +CharIndex(CHAR(16),[phone])+CharIndex(CHAR(17),[phone])+CharIndex(CHAR(18),[phone])+CharIndex(CHAR(19),[phone])
      +CharIndex(CHAR(20),[phone])+CharIndex(CHAR(21),[phone])+CharIndex(CHAR(22),[phone])+CharIndex(CHAR(23),[phone])
      +CharIndex(CHAR(24),[phone])+CharIndex(CHAR(25),[phone])+CharIndex(CHAR(26),[phone])+CharIndex(CHAR(27),[phone])
      +CharIndex(CHAR(28),[phone])+CharIndex(CHAR(29),[phone])+CharIndex(CHAR(30),[phone])+CharIndex(CHAR(31),[phone])
      +CharIndex(CHAR(127),[phone]) >0

如果测试结果是肯定的

以下UDF可用于通过更新从数据中删除控制字符

Update YourTable Set Phone=[dbo].[udf-Str-Strip-Control](Phone)

感兴趣的UDF

CREATE FUNCTION [dbo].[udf-Str-Strip-Control](@S varchar(max))
Returns varchar(max)
Begin
    ;with  cte1(N) As (Select 1 From (Values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) N(N)),
           cte2(C) As (Select Top (32) Char(Row_Number() over (Order By (Select NULL))-1) From cte1 a,cte1 b)
    Select @S = Replace(@S,C,' ')
     From  cte2

    Return LTrim(RTrim(Replace(Replace(Replace(@S,' ','><'),'<>',''),'><',' ')))
End
--Select [dbo].[udf-Str-Strip-Control]('Michael        '+char(13)+char(10)+'LastName')  --Returns: Michael LastName

正如所承诺的(并由比尔推动),以下是对UDF的一点评论。

  1. 我们传递一个我们想要删除控制字符的字符串
  2. 我们创建了一个ascii字符0 - 31
  3. 的临时计数表
  4. 然后我们对每个角色进行全局搜索和替换 理货表。找到的每个字符都将替换为空格
  5. 最后的字符串被剥去了重复的空格(一个小技巧 几周前戈登演示了 - 没有原版 链路)