标签:constrain 建表 不为 primary ast manage min 外键约束 来讲
约束(constraint):对创建的表的列属性、字段进行的限制。
诸如:not null/unique/primary key/foreign key/check
作用范围:
①列级约束仅仅能作用在一个列上
②表级约束能够作用在多个列上(当然表级约束也能够作用在一个列上)
定义方式:列约束必须跟在列的定义后面,表约束不与列一起,而是单独定义。
— —NOT NULL:不为空约束,仅仅能定义在列级
CREATE TABLE employees( employee_id NUMBER(6), --<span style="color:#FF0000;">系统命名</span> last_name VARCHAR2(25) <span style="color:#FF0000;">NOT NULL</span>, salary NUMBER(8,2), commission_pct NUMBER(2,2), --<span style="color:#FF0000;">用户自己定义命名</span> hire_date DATE <span style="color:#FF0000;">CONSTRAINT emp_hire_date_nn NOT NULL</span>,能够在PL/SQLDEV的My objects-Tables-employees-Check constraints中查看该表的约束。
— —UNIQUE:唯一约束,能够定义在表级或列级
CREATE TABLE employees( employee_id NUMBER(6), --<span style="color:#FF0000;">列级,系统命名唯一约束</span> last_name VARCHAR2(25) <span style="color:#FF0000;">UNIQUE</span>, email VARCHAR2(25), salary NUMBER(8,2), commission_pct NUMBER(2,2), hire_date DATE NOT NULL, ... --<span style="color:#FF0000;">表级,用户自己定义命名唯一约束</span> CONSTRAINT <span style="color:#FF0000;">emp_email_uk</span> UNIQUE(email));
— —PRIMARY KEY :主键,能够定义在表级或列级
CREATE TABLE departments( department_id NUMBER(4), department_name VARCHAR2(30) CONSTRAINT dept_name_nn NOT NULL, manager_id NUMBER(6), location_id NUMBER(4), CONSTRAINT dept_id_pk <span style="color:#FF0000;">PRIMARY KEY</span>(department_id));
— —FOREIGN KEY: 外键,在表级指定子表中的列
— —REFERENCES: 标示在父表中的列
— —ON DELETE CASCADE(级联删除): 当父表中的列被删除时。子表中相相应的列也被删除
— —ON DELETE SET NULL(级联置空): 子表中对应的列置空
constraint emp1_dept_id_fk <span style="color:#FF0000;">foreign key</span>(dept_id) <span style="color:#FF0000;">references</span> departments(department_id) <span style="color:#FF0000;">ON DELETE CASCADE</span>
— —CHECK :定义每一行必须满足的条件
..., salary NUMBER(2) CONSTRAINT emp_salary_min CHECK (salary > 0),...
create table emp1( employee_id number(8), salary number(8), --<span style="color:#FF0000;">列级约束</span> hire_date date not null, dept_id number(8), email varchar2(8) constraint emp1_email_uk unique, name varchar2(8) constaint emp1_name_uu not null, first_name varchar2(8), --<span style="color:#FF0000;">表级约束</span> constraint emp1_emp_id_pk primary key(employee_id), constraint emp1_fir_name_uk unique(first_name), --<span style="color:#FF0000;">外键约束</span> constraint emp1_dept_id_fk foreign key(dept_id) <span style="color:#FF0000;">references</span> departments(department_id) ON DELETE CASCADE )
alter table emp1 add constaint emp1_sal_ck check(salary > 0)
alter table emp1 modify (salary not null)
alter table emp1 drop constaint emp1_sal_ck
alter table emp1 enable constraint emp1_email_uk;
oracle约束总结(not null/unique/primary key/foreign key/check)
标签:constrain 建表 不为 primary ast manage min 外键约束 来讲
原文地址:http://www.cnblogs.com/cxchanpin/p/6907756.html