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

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

    Believe it or not, in my system this ugly function performs better than G Mastros elegant one.

    CREATE FUNCTION dbo.RemoveSpecialChar (@s VARCHAR(256)) 
    RETURNS VARCHAR(256) 
    WITH SCHEMABINDING
        BEGIN
            IF @s IS NULL
                RETURN NULL
            DECLARE @s2 VARCHAR(256) = '',
                    @l INT = LEN(@s),
                    @p INT = 1
    
            WHILE @p <= @l
                BEGIN
                    DECLARE @c INT
                    SET @c = ASCII(SUBSTRING(@s, @p, 1))
                    IF @c BETWEEN 48 AND 57
                       OR  @c BETWEEN 65 AND 90
                       OR  @c BETWEEN 97 AND 122
                        SET @s2 = @s2 + CHAR(@c)
                    SET @p = @p + 1
                END
    
            IF LEN(@s2) = 0
                RETURN NULL
    
            RETURN @s2
    

提交回复
热议问题