首页 > 解决方案 > 如何在 SQL 中检查电话号码的有效性

问题描述

我编写了以下查询来打印电话号码不是 10 位数字或包含任何字母但它不起作用的所有行。有人可以告诉我为什么它不起作用

SELECT * FROM table_name WHERE Phone_number NOT LIKE '[0-9]*10';

标签: sqlregexoracle

解决方案


考虑到电话号码有更复杂的规则,你可以使用这样的东西。

我展示了不同的前提,你可以得到一个更好的主意:

数据演示

SQL> create table test_phone ( phone_number varchar2(20) ) ;

Table created.

SQL> insert into test_phone values ( '4429239220' ); -- 10 digits

1 row created.

SQL> insert into test_phone values ( '10229383890' ); -- 11 digits 

1 row created.

SQL>  insert into test_phone values ( 'GE4914098998833' ); -- contains letters

1 row created.

SQL> insert into test_phone values ( 'AGCD292911' ); -- 10 digits but letters

 1 row created.

前提:仅10位数字

SQL> select * from test_phone where regexp_like(phone_number,'^[[:digit:]]{10}$') ;

PHONE_NUMBER
--------------------
4429239220

前提(10位或任何带字母的数字)

SQL>  select * from test_phone where regexp_like(phone_number,'^[a-zA-Z0-9-]{10}*$');

PHONE_NUMBER
--------------------
4429239220
AGCD292911

前提不是(10位数字或字母)

SQL>  select * from test_phone where not regexp_like(phone_number,'^[a-zA-Z0-9-]{10}*$');

PHONE_NUMBER
--------------------
10229383890
GE4914098998833

前提:只有那些不是 10 位数字且不包含任何字母的记录。无需正则表达式即可实现

SQL> select * from test_phone where lengthc(phone_number) != 10 and validate_conversion(phone_number as number)=1
  2  ;

PHONE_NUMBER
--------------------
10229383890

推荐阅读