約束:保證數(shù)據(jù)庫(kù)有某些特定的商業(yè)邏輯,維護(hù)數(shù)據(jù)的完整性:約束、觸發(fā)器、應(yīng)用程序(過(guò)程、函數(shù))
Oracle中,約束分為5種
1、非空約束:如果給某個(gè)字段定義了not null,name在插入數(shù)據(jù)的時(shí)候,就必須為給字段提供數(shù)據(jù)。
--創(chuàng)建表的時(shí)候添加非空約束
create table user_table(
username varchar2(20) not null,
password varchar2(20)
);
--修改表的時(shí)候添加非空約束
alter table table_name modify 字段名 字段類型 not null;
--刪除非空約束
alter table table_name modify 字段名 字段類型 null;
主鍵約束(primary key):主鍵是定位表中單個(gè)行的方式,可以唯一標(biāo)識(shí)表中的數(shù)據(jù),關(guān)系型數(shù)據(jù)庫(kù)每一張表都應(yīng)該有主鍵,主鍵可以是一個(gè)字段也可以是多個(gè)字段
1、主鍵列必須非空且唯一
2、每張表只能有一個(gè)主鍵,不過(guò)這個(gè)主鍵可以由多個(gè)字段共同組成(聯(lián)合主鍵)
--在創(chuàng)建表的時(shí)候添加主鍵約束
--列級(jí)約束
create table student_table(
student_id number(10) primary key,
student_name varchar2(20)
);
表級(jí)約束
create table student_table(
student_id number(10),
student_name varchar2(20),
constraint pk_student_id primarykey(student_id)?
);
user_constraints?
sql developer
--修改表的時(shí)候添加主鍵約束
alter table table_name add constraint 約束的名字 primary key(.....);
--刪除主鍵約束
alter table tablename drop constraint 約束的名字 alter table tablename drop primary key;
alter table tablename disable|enable constraint 約束的名字;
外鍵(foreign key):
用于聯(lián)系主表和從表之間的關(guān)系,外鍵定義在從表上的,
要求外鍵數(shù)據(jù)必須在主表的主鍵列中存在或者為null;
--在創(chuàng)建表的時(shí)候設(shè)置外鍵約束
列級(jí)約束:
create tablebriup_dept(? --主表
deptno number(2) primary key,
dname varchar2(20),
loc varchar2(20)
);
create tablebriup_emp(??? --從表
ename varchar2(20) constraint 約束的名字 not null,
deptno number(2) references briup_dept(deptno)
);
表級(jí)約束:
create tablebriup_emp(??? --從表
ename varchar2(20) not null,
deptno number(2),
constraint fk_emp_deptno_dept_deptno foreign key references briup_dept(deptno) [on delete cascade];
);
--刪除外鍵約束
alter table tablename drop constraint 約束的名字 alter table tablename disable|enable constraint 約束的名字;
4、唯一約束
unique
--創(chuàng)建表的時(shí)候添加唯一約束
create table test(
username varchar2(20) unique
);
create table test(
username varchar2(20),
constraint 約束的名字 unique(字段);
);
--在修改的時(shí)候
alter table table_name add constraint 約束的名字 unique(.....);
--刪除唯一約束
alter table tablename drop constraint 約束的名字 alter table tablename disable|enable constraint 約束的名字;
5、檢查約束
--在創(chuàng)建的時(shí)候添加檢查約束
create table emp(
sex varchar2(20) default '男' check(sex in ('男' ,'女')),?
sal number(5) check(sal>0)
);
--修改
alter table table_name add constraint 約束的名字 check(條件);
--刪除
alter table tablename drop constraint 約束的名字 alter table tablename disable|enable constraint 約束的名字;