如何验证student_name,以便只能在其中输入字母字符?

时间:2012-04-30 19:50:28

标签: oracle oracle10g

如何验证student_name表中的student列是否只能输入字母字符?

3 个答案:

答案 0 :(得分:3)

如果“仅字母字符”仅表示大写和小写字母A-Z,则可以使用CHECK约束来检查是否存在非字母字符

SQL> ed
Wrote file afiedt.buf

  1  create table student (
  2    student_name varchar2(100),
  3    constraint chk_student_name check( student_name = regexp_replace( student_name, '[^[:alpha:]]', null ))
  4* )
SQL> /

Table created.

这允许您插入纯粹按字母顺序排列的student_name

SQL> insert into student values( 'JustinCave' );

1 row created.

但是如果你插入像字母一样非字母的东西

,则会引发错误
SQL> insert into student values( 'Justin Cave' );
insert into student values( 'Justin Cave' )
*
ERROR at line 1:
ORA-02290: check constraint (SCOTT.CHK_STUDENT_NAME) violated

如果要允许空格和字母字符,可以修改正则表达式

SQL> ed
Wrote file afiedt.buf

  1  create table student (
  2    student_name varchar2(100),
  3    constraint chk_student_name check( student_name = regexp_replace( student_name, '[^([:alpha:]|[:space:])]', null ))
  4* )
SQL> /

Table created.

SQL> insert into student values( 'Justin Cave' );

1 row created.

SQL> insert into student values( 'Justin Cave1' );
insert into student values( 'Justin Cave1' )
*
ERROR at line 1:
ORA-02290: check constraint (SCOTT.CHK_STUDENT_NAME) violated

答案 1 :(得分:0)

您可能正在寻找检查约束

语法可能类似于create table命令中的以下内容:

... CHECK REGEXP_LIKE (students_name, '^([:alpha:]|[:space:])*$'), ...

我到目前为止在网上找到的例子:

http://www.w3schools.com/sql/sql_check.asp

http://psoug.org/reference/regexp.html

答案 2 :(得分:0)

您可以使用Oracle的REGEXP函数来执行此操作。