create table product (
Pname varchar2(20) unique,
Pdate date not null,
PID number(5) primary key,check(PID>10000 AND PID<=99999),
Ploc char(30) default '北京')
要点就是在列的结尾直接添加,如果同一列有多个约束,通过逗号来分隔
有个问题,通过数字字典来查询约束,我们得到的是系统提供的名字并且约束的类型不好区分。
SQL> select constraint_name,constraint_type from user_constraints where table_name = 'PRODUCT';
CONSTRAINT_NAME CONSTRAINT_TYPE
------------------------------------------------------------ --
SYS_C009539 C
SYS_C009540 C
SYS_C009541 P
SYS_C009542 U
U:表示unique
P:primary key
C:check或者default
查看列的默认值:
SQL> select column_name,datA_dEfault from useR_tab_columns where table_name = 'PRODUCT';
COLUMN_NAME DATA_DEFAULT
------------------------------------------------------------ --------------------------------------------------------------------------------
PNAME
PDATE
PID
PLOC '北京'
Create table product(
PID number(5),
PNAME varchar2(20),
PDATE date constraint NN_PDATE_PRODUCT not null,
PLOC char(30) default ‘北京’,
FKDEPTNO number(5),
Constraint UK_PNAME_PRODUCT unique(PNAME),
Constraint PK_PID_PRODUCT primary key(PID),
Constraint CK_PID_PRODUCT check(PID>10000 AND PID<9999),
Constraint FK_DEPTNO foreign key (FKDEPTNO) references dept(DEPTNO)
);
SQL> select constraint_name,constraint_type from user_constraints where table_name = 'PRODUCT';
CONSTRAINT_NAME CO
------------------------------------------------------------ --
NN_PDATE_PRODUCT C
CK_PID_PRODUCT C
PK_PID_PRODUCT P
UK_PNAME_PRODUCT U
FK_DEPTNO_PRODUCT R
删除约束
Alter table product drop primary key;
Alter table product drop constraint PK_PID_PRODUCT;
Alter table product drop unique (PNAME);
Alter table product modify(PDATE,null);
Alter table product modify(PLOC,default null)/modify(PLOC ,default ‘威海’);--更改默认值
Alter table product drop constraint FK_DEPTNO;
外键、check约束只能使用约束名来删除,其他约束如果有约束名也可以使用约束名来删除
增加约束
Alter table product add primary key (PID);
Alter table product add constraint PK_PID primary key(PID);
Alter table product add unique(PNAME);
Alter table product modify(PDATE, not null);
Alter table product modify(PLOC ,default ‘威海’);