SQL Server search using like while ignoring blank spaces

后端 未结 1 475
南笙
南笙 2020-12-04 04:10

I have a phone column in the database, and the records contain unwanted spaces on the right. I tried to use trim and replace, but it didn\'t return the correct

相关标签:
1条回答
  • 2020-12-04 04:22

    Given the sample data, I suspect you have control characters in your data. For example char(13), char(10)

    To confirm this, just run the following

    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
    

    If the Test Results are Positive

    The following UDF can be used to strip the control characters from your data via an update

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

    The UDF if Interested

    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
    

    As promised (and nudged by Bill), the following is a little commentary on the UDF.

    1. We pass a string that we want stripped of Control Characters
    2. We create an ad-hoc tally table of ascii characters 0 - 31
    3. We then run a global search-and-replace for each character in the tally-table. Each character found will be replaced with a space
    4. The final string is stripped of repeating spaces (a little trick Gordon demonstrated several weeks ago - don't have the original link)
    0 讨论(0)
提交回复
热议问题