一、约束包括(非空约束,主键约束、外键约束、唯一约束以及检查约束),作用是定义规则,确保数据的完整性;
1、非空约束:
创建时:CREATE TABLE table_name(column_name datatype NOT NULL,...)
修改时:ALTER TABLE table_name MODIFY column_name datatype NOT NULL;
去除时:ALTER TABLE table_name MODIFY colunm_name datatype NULL;
2、主键约束(确保表中每一行数据的唯一性,非空且唯一):一张表只能有一个主键约束,主键约束可以由多个字段构成(联合主键或复合主键)
创建表时添加:CREATE TABLE table_name (column_name datatype PRIMARY KEY,...);
创建表时添加联合主键:CONSTRAINT constraint_name PRIMARY KEY (column1,column2,...);
eg:create table tbl_user(id number(6),username varchar2(20),password varchar2(20),constraint pk_id_username primary key (id,username));
查询某个表的约束:select constraint_name,constraint_type from user_constraints where table_name = 'TBL_USER';(表名大写)
修改表时添加主键约束:ALTER TABLE table_name ADD CONSTRAINT constraint_name PRIMARY KEY (column_name1,......);
更改约束名称:ALTER TABLE table_name RENAME CONSTRAINT constraint_name TO new_constraint_name;
禁用|启用主键约束:ALTER TABLE table_name DISABLE|ENABLE CONSTRAINT constraint_name;
删掉约束:ALTER TABLE table_name DROP CONSTRAINT constraint_name;
删除主键约束:ALTER TABLE table_name DROP PRIMARY KEY[CASCADE]
注:CASCADE是级联的意思,如果此主键是其他表外键,删除时会删掉其他表的外键
3、外键约束
创建表时添加主键约束:CREATE TABLE table1 (column_name datatype REFERENCES table2(column_name),...);
注:table2是主表,table1是从表
eg:create table tbl_type(typeid varchar2(10) primary key,typename varchar2(20)); --创建主表
create table tbl_userinfo(id varchar2(10) primary key,username varchar2(20),typeid_new varchar2(10) references tbl_type(typeid));--创建从表
插入从表的外键值时需为主表的主键值或null;
表级设置外键约束:CONSTRAINT constraint_name FOREIGN KEY(column_name) REFERENCES table_name(column_name)[ON DELETE CASCADE];
注:级联删除:主表删除了主键的值,从表使用主表主键值的行也会被删除掉。
修改表时添加外键约束:ALTER TABLE table_name ADD CONSTRAINT constraint_name FOREIGN KEY(column_name) REFERENCES table_name(column_name) [ON DELETE CASCADE];
禁用|启用外键约束:ALTER TABLE table_name DISABLE|ENABLE CONSTRAINT constraint_name;
删掉外键约束:ALTER TABLE table_name DROP CONSTRAINT constraint_name;
4、唯一约束(主键约束字段值必须是非空的,唯一约束允许有一个空值,主键在每张表中能有一个,唯一约束在每张表中可以有多个)
创建表时添加列级唯一约束:CREATE TABLE table_name (column_name datatype UNIQUE,...);
创建表时添加表级唯一约束:CONSTRAINT constraint_name UNIQUE(conlumn_name);
修改表时添加唯一约束:ALTER TABLE table_name ADD CONSTRAINT constraint_name UNIQUE (column_name1);
禁用|启用唯一约束:ALTER TABLE table_name DISABLE|ENABLE CONSTRAINT constraint_name;
删掉唯一约束:ALTER TABLE table_name DROP CONSTRAINT constraint_name;
5、检查约束
创建表时添加列级检查约束:CREATE TABLE table_name(column_name datatype CHECK(expressions),...);
创建表时添加表级检查约束:CONSTRAINT constraint_name CHECK(expressions);
修改表时添加检查约束:ADD CONSTRAINT constraint_name CHECK(expressions);
禁用|启用检查约束:ALTER TABLE table_name DISABLE|ENABLE CONSTRAINT constraint_name;
删掉检查约束:ALTER TABLE table_name DROP CONSTRAINT constraint_name;