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

后端 未结 18 1344
情深已故
情深已故 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条回答
  •  别那么骄傲
    2020-11-22 00:21

    Try this function:

    Create Function [dbo].[RemoveNonAlphaCharacters](@Temp VarChar(1000))
    Returns VarChar(1000)
    AS
    Begin
    
        Declare @KeepValues as varchar(50)
        Set @KeepValues = '%[^a-z]%'
        While PatIndex(@KeepValues, @Temp) > 0
            Set @Temp = Stuff(@Temp, PatIndex(@KeepValues, @Temp), 1, '')
    
        Return @Temp
    End
    

    Call it like this:

    Select dbo.RemoveNonAlphaCharacters('abc1234def5678ghi90jkl')
    

    Once you understand the code, you should see that it is relatively simple to change it to remove other characters, too. You could even make this dynamic enough to pass in your search pattern.

    Hope it helps.

提交回复
热议问题