SQL 使用 like 忽略空格进行服务器搜索

SQL Server search using like while ignoring blank spaces

我在数据库中有一个 phone 列,记录的右侧包含不需要的空格。我尝试使用 trim 并替换,但没有 return 正确的结果。

如果我使用

phone like '%2581254%'

它returns

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

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

所以如果我这样使用它

 phone like '%2581254'

我什么也没得到,因为右边有空格!

所以我尝试用trim替换,结果只有一个

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

returns

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

请注意,这四个 id 具有相同的 phone 编号!

Table数据

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

我添加了很多号码进行测试

php 函数获取最后 7 位数字并进行比较。

例如

01532388254 will be 2581254

我想搜索所有在 phone 号码中有这 7 位数字的用户 2581254

我想不通哪里出了问题!

它应该 return 4 个 ID 而不是 1 个 ID

根据示例数据,我怀疑您的数据中有 控制字符。例如 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

正如所承诺的(在 Bill 的推动下),以下是对 UDF 的一些评论。

  1. 我们传递一个我们想要去除控制字符的字符串
  2. 我们创建一个 ascii 字符 0 - 31
  3. 的临时计数 table
  4. 然后我们 运行 对每个字符进行全局搜索和替换 理货-table。找到的每个字符都将替换为 space
  5. 最后的字符串去掉了重复的spaces(一个小技巧 几周前戈登演示过——没有原件 link)