And database integrity constraints

Integrity of the database

Database constraint is to ensure the integrity of the database , database integrity divided entity integrity, and referential integrity field

Entity integrity

Entity integrity requires that the primary key fields of the table can not be empty and can not be repeated;

Domain integrity

Domain integrity requirements of data tables within the effective range;

Referential integrity

Referential integrity ensures the consistency of the data table associated;

Use constraints

Constraint is to ensure data integrity and consistency of the table means is divided into a primary key constraint , foreign key constraints , check constraints , the only constraint , non-null constraint five kinds;

The primary key constraint

Only one primary key constraint in each data table, the primary key constraint can have multiple columns;

-- 添加主键约束
alter table table_name add constraints constraint_name primary key(column_name);

-- 移除主键约束
alter table table_name drop constraint constraint_name;

-- 创建表时添加主键
primary key(column_name)

Foreign key constraint

Foreign key constraint is to ensure that the data column using primary key constraint foreign key columns are consistent can have multiple foreign keys;

-- 创建表时添加外键约束, on delete cascade 代表级联删除
constraint constraint_name foregn key(column_name) reference table_name(column_name)
   on delete cascade;

-- 添加外键约束
alter table table_name add constraint constraint_name foregn key(column_name) 
   reference table_name(column_name) on delete cascade;

-- 移除外键约束
alter table table_name drop constraint constraint_name

Check constraints

Check constraint is to ensure the correctness of the data columns

-- 添加检查约束
alter table table_name add constraint constraint_name check(condition)

condition bit checking condition, such condition is defined on the age of 18-25 age> 18 and age <25

The only constraint

The only constraint on the data to ensure the uniqueness of the column, and a primary key constraint similar but the only constraint may have a plurality of

-- 添加检查约束
alter table table_name add constraint constraint_name unique(condition)

Non-empty constraint

Ensure non-null constraint on the column must have a value

alter table table_name modify column_name not null

Exercise

-- system 用户
-- 授权/回收用户Flynn 创建表权限
grant create table to flynn;
revoke create table from flynn;

-- flynn 用户
-- 创建t_user表
create table t_user(
   u_name char(10) not null,
   u_age number(5) not null,
   U_password varchar(20) not null
);

-- 添加主键约束
alter table t_user add constraints pk_uname primary key(u_name);

-- 移除主键约束
alter table t_user drop constraint pk_uname;


select * from t_user;



-- 查询一个用户拥有的对象权限
select * from dba_tab_privs where grantee='用户名';

-- 查询一个用户拥有的系统权限
select * from dba_sys_privs where grantee='用户名';

Guess you like

Origin www.cnblogs.com/f1ynn/p/11619468.html