oracle alter关键字练习收获

create table zpart_student(
student_id number(7) primary key ,
student_name varchar2(10) not null,
sex varchar2(1) default 'f' not null check(sex in('m','f')),
age number(3) not null,
score number(4,1) not null,
email varchar2(30) not null check(email like'%@%'),
course_id number(3) references course(id)
)

drop table zpart_student;

create table course(
id number(3) primary key,
name varchar2(30) not null
)

select * from user_constraints where table_name='ZPART_STUDENT'--这张表记录的一个约束的名字,类型,来自于哪张表
select * from user_cons_columns where table_name='ZPART_STUDENT';--这张表记录了一个约束的名字,来自于那个字段和哪张表


alter table zpart_student modify(sex null);
alter table zpart_student drop primary key;--可以通过无名方式删除主键,因为一个表的主键唯一
alter table zpart_student add primary key(student_id);--可以通过无名方式添加一个表的主键
alter table zpart_student add unique(email);--可以通过无名方式添加一个表某个字段的唯一约束
alter table zpart_student drop unique(email);--可以通过无名方式删除一个表某个字段的唯一约束
alter table zpart_student add check(sex is not null);--非空约束可以通过检查约束来表示,检查约束可以无名添加
alter table zpart_student drop check(sex in('f','m'));--检查约束不可无名删除
alter table zpart_student add foreign key(course_id) references course(id);--外键约束可无名添加
alter table zpart_student drop foreign key(course_id) references course(id);--外键约束不可无名删除
--由以上例子可见:约束皆可无名添加(not null通过modify无名添加),只有主键约束和唯一约束能无名删除
--通过从user_constraints和user_cons_columns查询无名约束的名字,通过排除法确定是哪个无名约束
select t1.CONSTRAINT_NAME,
t1.TABLE_NAME,
t1.CONSTRAINT_TYPE,
t2.COLUMN_NAME
from user_constraints t1
inner join user_cons_columns t2
on t1.CONSTRAINT_NAME = t2.CONSTRAINT_NAME and t1.TABLE_NAME=t2.TABLE_NAME
where t1.table_name='ZPART_STUDENT'order by t2.column_name;

猜你喜欢

转载自www.cnblogs.com/JustDoIt-Fei/p/9292356.html