我可以只允许为 Oracle 10G 中的 table 输入某些特定字符串吗?

Can I allow only certain specific strings to be inputted for a table in Oracle 10G?

CREATE TABLE trial (
    phone_number NUMBER(5) PRIMARY KEY;
    name VARCHAR2(20)
)

在这个 table 中,我想要一个约束,这样输入的名称只能是 'trial'、'experiment' 或 'test'.

您可以添加 CHECK 约束,如下所示:

ALTER TABLE trial  
ADD CONSTRAINT name_CHK CHECK (NAME IN ('trial','experiment','test'));

如果您不想在名称中使用空值,那么您还可以在 name 列上使用 NOT NULL 约束。

创建table时,您可以使用其中的Constraint,如下所示:

CREATE TABLE trial (
    phone_number NUMBER(5) PRIMARY KEY;
    name VARCHAR2(20) not null,
    CONSTRAINT name_CHK CHECK (NAME IN ('trial','experiment','test')
);

使用 CHECK 约束:

CREATE TABLE trial (
    phone_number NUMBER(5)
                 CONSTRAINT trial__phone_number__pk PRIMARY KEY,
    name         VARCHAR2(20)
                 NOT NULL
                 CONSTRAINT trial__name__ck CHECK (
                   name IN ( 'trial', 'experiment', 'test' )
                 )
);

然后:

INSERT INTO trial ( phone_number, name )
SELECT 1, 'trial' FROM DUAL UNION ALL
SELECT 2, 'experiment' FROM DUAL UNION ALL
SELECT 3, 'test' FROM DUAL;

有效但是:

INSERT INTO trial ( phone_number, name ) VALUES ( 4, 'not valid' );

输出:

ORA-02290: check constraint (SCHEMA_NAME.TRIAL__NAME__CK) violated

db<>fiddle here

这是一个check约束:

SQL> create table trial
  2    (phone_number number(5) primary key,
  3     name         varchar2(20) constraint ch_tri_nam check
  4                                 (name in ('trial', 'experiment', 'test'))
  5    );

Table created.

SQL> insert into trial (phone_number, name) values (1, 'trial');

1 row created.

SQL> insert into trial (phone_number, name) values (1, 'what');
insert into trial (phone_number, name) values (1, 'what')
*
ERROR at line 1:
ORA-02290: check constraint (SCOTT.CH_TRI_NAM) violated


SQL>

或者,您可以使用消息更具描述性的触发器(检查约束只说明它被违反;在触发器中,您可以创建自己的消息)。

SQL> create table trial
  2    (phone_number number(5) primary key,
  3     name         varchar2(20)
  4    );

Table created.

SQL> create or replace trigger trg_biu_trial
  2    before insert or update on trial
  3    for each row
  4  begin
  5    if nvl(:new.name, :old.name) not in ('trial', 'experiment', 'test') then
  6       raise_application_error(-20000, 'Invalid name; allowed values are: trial, experiment, test');
  7    end if;
  8  end;
  9  /

Trigger created.

SQL> insert into trial (phone_number, name) values (1, 'trial');

1 row created.

SQL> insert into trial (phone_number, name) values (1, 'what');
insert into trial (phone_number, name) values (1, 'what')
            *
ERROR at line 1:
ORA-20000: Invalid name; allowed values are: trial, experiment, test
ORA-06512: at "SCOTT.TRG_BIU_TRIAL", line 3
ORA-04088: error during execution of trigger 'SCOTT.TRG_BIU_TRIAL'


SQL>