简体   繁体   English

如何从 SQL 的列中删除所有非字母字符?

[英]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).我希望通过从列值中删除任何数字或特殊字符并仅保留字母值 (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. @lptr在评论中发布了一个有趣的想法,极大地激发了这个答案。

First use TRANSLATE to get a list of characters that need to be cleaned.首先使用TRANSLATE获取需要清理的字符列表。 Then call TRANSLATE again using this list and replacing them all with a space.然后使用此列表再次调用TRANSLATE并将它们全部替换为空格。 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    |
+---------------------+-------------------+---------+

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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