数据库相关资料

--check约束(只能是列级约束)
create table emp_sicheng_06(
id number(10),
name varchar2(20) constraint emp_sicheng_name_nn not null,
salary number(10,2) check(salary>15000 and salary<20000),
--表级约束
constraint emp_sicheng_id_pk primary key(id)
)
insert into emp_sicheng_06 values(1,'李四',1600);--违反唯一约束条件
insert into emp_sicheng_06 values(1,'李四',16000);
--解决方案
--1.先删除字表中的记录,在删除父表中的记录
--2.使用级联删除
create table emp_sicheng_07(
id number(2),
name varchar2(20),
department_id number(10),
--表级约束
constraint emp_sicheng_07_fk foreign key(department_id)
references departments(department_id) on delete cascade
);
select * from emp_sicheng_07


--小结:
--1.如何在建表的同时添加列级约束和表级约束
--2.非空只能是列级约束并且唯一约束对空值(null)无效
--3.表级约束只能在建表的同时添加
--4.外键约束:on delete cascade(级联删除):
--当附表中的列被删除时,字表中相对应的列也被删除
--on delete set null:(级联置空)
--当附表中的列被置空时,字表中相应的列置空
--字表在进行插入操作时,关联字段的值必须是父表已经存在的值
--父表在执行删除时,必须要先将字表中关联字段对应的值删除才能成功


--建表之后添加约束
--使用alter table语句
--添加或删除约束,但是不能修改
--有效化约束和无效化约束
--ps:添加not null 约束必须要使用modify语句

--建表之后添加非空约束
alter table emp_sicheng_07 modify(id number(10) not null)

--建表之后删除唯一约束
alter table emp_sicheng_07 drop (emp_sicheng_07表的唯一约束名字)

--删除非空约束
alter table emp_sicheng_07 drop constraint(非空约束名字)

--建表之后添加唯一约束
alter table emp_sicheng_07 add constraint (添加emp_sicheng_07表唯一约束名字) unique (表中的字段名)
--ps:有值的情况下添加不一定成功

--约束无效化
--在alter table语句中使用disable子句将约束无效化
--但不会删除约束
alter table emp disable constraint (表的约束条件)

insert into emp values(1,'张三',1);
commit;
--约束有效化
alter table emp enable constraint (emp表中约束的名字)
--ps:如果表中已经存在了相同的值,则该语句无法执行
 

猜你喜欢

转载自blog.csdn.net/CXY_ZPH/article/details/86530805
今日推荐