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

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

    From performance perspective I'd use Inline Function:

    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE FUNCTION [dbo].[udf_RemoveNumericCharsFromString]
    (
    @List NVARCHAR(4000)
    )
    RETURNS TABLE 
    AS RETURN
    
        WITH GetNums AS (
           SELECT TOP(ISNULL(DATALENGTH(@List), 0))
            n = ROW_NUMBER() OVER(ORDER BY (SELECT NULL))
            FROM
              (VALUES (0),(0),(0),(0)) d (n),
              (VALUES (0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) e (n),
              (VALUES (0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) f (n),
              (VALUES (0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) g (n)
                )
    
        SELECT StrOut = ''+
            (SELECT Chr
             FROM GetNums
                CROSS APPLY (SELECT SUBSTRING(@List , n,1)) X(Chr)
             WHERE Chr LIKE '%[^0-9]%' 
             ORDER BY N
             FOR XML PATH (''),TYPE).value('.','NVARCHAR(MAX)')
    
    
       /*How to Use
       SELECT StrOut FROM dbo.udf_RemoveNumericCharsFromString ('vv45--9gut')
       Result: vv--gut
       */
    

提交回复
热议问题