简体   繁体   中英

How to remove all non-alphabetic characters from a column in SQL?

I'm looking to clean name columns by removing any numeric or special characters from the column values and leaving only alphabetic values (AZ).

I've tried this so far to make the column all uppercase and trim leading/trailing whitespaces:

upper(trim([Name])) [Name]

I'm stuck on how to proceed from here, any help is appreciated!

Firstly if this is for peoples' names then this is a terrible idea.

Globally names can certainly contain spaces, punctuation characters, accented characters and non Latin characters (and even numbers).

Nonetheless there may be other legitimate use cases for wanting to "remove all non-alphabetic characters from a column"

@lptr posted an interesting idea in the comments that heavily inspires this answer.

First use TRANSLATE to get a list of characters that need to be cleaned. Then call TRANSLATE again using this list and replacing them all with a space. Finally remove all spaces and convert to uppercase as desired in your case.

DECLARE @t TABLE
  (
     colX VARCHAR(100)
  );

INSERT INTO @t
            (colX)
VALUES     ('@#£ab£cd&123x/=+xz'),
            ('%-+=/;:,.abc@#£&*()'),
            ('abc@#£&*() z')

SELECT *,
       Cleaned = UPPER(REPLACE(translate(colx, bad_chars, SPACE(len(bad_chars))), ' ', ''))
FROM   @t
       CROSS APPLY (VALUES(replace(translate(colx, 'abcdefghijklmnopqrstuvwxyz' COLLATE Latin1_General_100_CI_AS, replicate('a', 26)), 'a', '') + '~')) V(bad_chars) 

Returns

+---------------------+-------------------+---------+
|        colX         |     bad_chars     | Cleaned |
+---------------------+-------------------+---------+
| @#£ab£cd&123x/=+xz  | @#££&123/=+~      | ABCDXXZ |
| %-+=/;:,.abc@#£&*() | %-+=/;:,.@#£&*()~ | ABC     |
| abc@#£&*() z        | @#£&*() ~         | ABCZ    |
+---------------------+-------------------+---------+

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM