How to strip all non-alphabetic characters from string in SQL Server?

后端 未结 18 1305
情深已故
情深已故 2020-11-21 23:49

How could you remove all characters that are not alphabetic from a string?

What about non-alphanumeric?

Does this have to be a custom function or are there

18条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 00:38

    If you are like me and don't have access to just add functions to your production data but still want to perform this kind of filtering, here's a pure SQL solution using a PIVOT table to put the filtered pieces back together again.

    N.B. I hardcoded the table up to 40 characters, you'll have to add more if you have longer strings to filter.

    SET CONCAT_NULL_YIELDS_NULL OFF;
    
    with 
        ToBeScrubbed
    as (
        select 1 as id, '*SOME 222@ !@* #* BOGUS !@*&! DATA' as ColumnToScrub
    ),
    
    Scrubbed as (
        select 
            P.Number as ValueOrder,
            isnull ( substring ( t.ColumnToScrub , number , 1 ) , '' ) as ScrubbedValue,
            t.id
        from
            ToBeScrubbed t
            left join master..spt_values P
                on P.number between 1 and len(t.ColumnToScrub)
                and type ='P'
        where
            PatIndex('%[^a-z]%', substring(t.ColumnToScrub,P.number,1) ) = 0
    )
    
    SELECT
        id, 
        [1]+ [2]+ [3]+ [4]+ [5]+ [6]+ [7]+ [8] +[9] +[10]
        +  [11]+ [12]+ [13]+ [14]+ [15]+ [16]+ [17]+ [18] +[19] +[20]
        +  [21]+ [22]+ [23]+ [24]+ [25]+ [26]+ [27]+ [28] +[29] +[30]
        +  [31]+ [32]+ [33]+ [34]+ [35]+ [36]+ [37]+ [38] +[39] +[40] as ScrubbedData
    FROM (
        select 
            *
        from 
            Scrubbed
        ) 
        src
        PIVOT (
            MAX(ScrubbedValue) FOR ValueOrder IN (
            [1], [2], [3], [4], [5], [6], [7], [8], [9], [10],
            [11], [12], [13], [14], [15], [16], [17], [18], [19], [20],
            [21], [22], [23], [24], [25], [26], [27], [28], [29], [30],
            [31], [32], [33], [34], [35], [36], [37], [38], [39], [40]
            )
        ) pvt
    

提交回复
热议问题