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

后端 未结 18 1304
情深已故
情深已故 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:25

    Parameterized version of G Mastros' awesome answer:

    CREATE FUNCTION [dbo].[fn_StripCharacters]
    (
        @String NVARCHAR(MAX), 
        @MatchExpression VARCHAR(255)
    )
    RETURNS NVARCHAR(MAX)
    AS
    BEGIN
        SET @MatchExpression =  '%['+@MatchExpression+']%'
    
        WHILE PatIndex(@MatchExpression, @String) > 0
            SET @String = Stuff(@String, PatIndex(@MatchExpression, @String), 1, '')
    
        RETURN @String
    
    END
    

    Alphabetic only:

    SELECT dbo.fn_StripCharacters('a1!s2@d3#f4$', '^a-z')
    

    Numeric only:

    SELECT dbo.fn_StripCharacters('a1!s2@d3#f4$', '^0-9')
    

    Alphanumeric only:

    SELECT dbo.fn_StripCharacters('a1!s2@d3#f4$', '^a-z0-9')
    

    Non-alphanumeric:

    SELECT dbo.fn_StripCharacters('a1!s2@d3#f4$', 'a-z0-9')
    

提交回复
热议问题