Ahm*_*ssa 0 sql t-sql database sql-server sql-like
我phone在数据库中有一列,并且记录右侧包含不需要的空格.我试图使用修剪和替换,但它没有返回正确的结果.
如果我使用
phone like '%2581254%'
Run Code Online (Sandbox Code Playgroud)
它返回
customerid
-----------
33470
33472
33473
33474
Run Code Online (Sandbox Code Playgroud)
但我只需要在开头使用百分号或外卡,我只想匹配左侧.
所以,如果我像这样使用它
phone like '%2581254'
Run Code Online (Sandbox Code Playgroud)
我没有得到任何东西,因为右边的空间!
所以我尝试使用trim和replace,我只得到一个结果
LTRIM(RTRIM(phone)) LIKE '%2581254'
Run Code Online (Sandbox Code Playgroud)
回报
customerid
-----------
33474
Run Code Online (Sandbox Code Playgroud)
请注意,这四个ID具有相同的电话号码!
表数据
customerid phone
-------------------------------------
33470 96506217601532388254
33472 96506217601532388254
33473 96506217601532388254
33474 96506217601532388254
33475 966508307940
Run Code Online (Sandbox Code Playgroud)
我为测试提出了多个号码
php函数占用最后7位数并进行比较.
例如
01532388254 will be 2581254
Run Code Online (Sandbox Code Playgroud)
我想搜索他们的电话号码2581254中有这7位数的所有用户
我无法弄清楚问题出在哪里!
它应该返回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
Run Code Online (Sandbox Code Playgroud)
如果测试结果是肯定的
以下UDF可用于通过更新从数据中删除控制字符
Update YourTable Set Phone=[dbo].[udf-Str-Strip-Control](Phone)
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
正如所承诺的(并由比尔推动),以下是对UDF的一点评论.
| 归档时间: |
|
| 查看次数: |
733 次 |
| 最近记录: |