标签:not iss int 条件 示例 info rac nbsp lte
约束是表级的强制规定
有以下五种约束:
注意事项
表级约束和列级约束
作用范围:
①列级约束只能作用在一个列上
②表级约束可以作用在多个列上(当然表级约束也可以作用在一个列上)
定义方式:列约束必须跟在列的定义后面,表约束不与列一起,而是单独定义。
非空(not null) 约束只能定义在列上
定义约束
CREATE TABLE [schema.]table (column datatype [DEFAULT expr] [column_constraint], ... [table_constraint][,...]);
CREATE TABLE employees( employee_id NUMBER(6), first_name VARCHAR2(20), ... job_id VARCHAR2(10) NOT NULL, CONSTRAINT emp_emp_id_pk PRIMARY KEY (EMPLOYEE_ID));
定义约束
column [CONSTRAINT constraint_name] constraint_type,
column,... [CONSTRAINT constraint_name] constraint_type (column, ...),
NOT NULL 约束
UNIQUE 约束
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 PRIMARY KEY(department_id));
FOREIGN KEY 约束
可以定义在表级或列级:
CREATE TABLE employees( employee_id NUMBER(6), last_name VARCHAR2(25) NOT NULL, email VARCHAR2(25), salary NUMBER(8,2), commission_pct NUMBER(2,2), hire_date DATE NOT NULL, ... department_id NUMBER(4), CONSTRAINT emp_dept_fk FOREIGN KEY (department_id) REFERENCES departments(department_id), CONSTRAINT emp_email_uk UNIQUE(email));
FOREIGN KEY 约束的关键字
CHECK 约束
添加约束
使用 ALTER TABLE 语句:
ALTER TABLE table ADD [CONSTRAINT constraint] type (column);
以create table emp as select * from employees;为例,添加和删除约束 Alter table emp modify(empname varchar2(50) not null);
示例
ALTER TABLE employees ADD CONSTRAINT emp_manager_fk FOREIGN KEY ( manager_id ) REFERENCES employees ( employee_id );
删除约束
ALTER TABLE employees DROP CONSTRAINT emp_manager_fk;
无效化约束
ALTER TABLE employees DISABLE CONSTRAINT emp_emp_id_pk;
激活约束
ALTER TABLE employees ENABLE CONSTRAINT emp_emp_id_pk;
查询约束
SELECT constraint_name, constraint_type, search_condition FROM user_constraints WHERE table_name = ‘EMPLOYEES‘;
SELECT constraint_name, column_name FROM user_cons_columns WHERE table_name = ‘EMPLOYEES‘;
标签:not iss int 条件 示例 info rac nbsp lte
原文地址:https://www.cnblogs.com/loaderman/p/11738934.html