7.windows-oracle combat Lesson 7 - Constraints

Data integrity

     Integrity of the data used to ensure compliance with certain commercial database data and logic rules. Using the constraint data integrity, triggers, functions to implement the method. In these three methods, the constraining easy to maintain, with the best performance, so as preferred.

 Constraint: not null, unique (may be empty, can not be repeated), primary key, foreign key, check

A table can have only one primary key, but there may be a plurality of unique.

 

Case:

   An existing store database, there are three tables:

Commodity table goods (product number goodsId, trade name goodsName, unit price unitprice, merchandise category category, vendor provider);

Customers table customer (customer number customerId, name name, address address, email email, gender sex, identity card cardId);

Buy purchase (customer number customerId, product number goodsId, purchase quantity nums);

1. The construction of the table, is defined in claim as follows:

 (1) Each table has a primary foreign keys;

 (2) the customer's name can not be null;

 (3) Unit must be greater than 0, the purchase data must be between 1 to 30;

 (4) e-mail can not be repeated

  (5) the customer is sex between men and women, the default is male

goods:

create table goods (goodsId char (8 ) primary key, - the master key, the master key is a name assigned by the system
goodsName VARCHAR2 (30),
UnitPrice Number (10,2) Check (UnitPrice> 0),
category VARCHAR2 (. 8),
Provider VARCHAR2 (30));

customer:

create table customer(customerId number(8) primary key,--主键
name varchar2(50) not null,
address varchar2(50),
email varchar2(50)  unique,
sex  char(2) default '男' check(sex in('男','女')),
cardId  char(18)  not null);

purchase:

create table purchase(customerId number(8) references customer(customerId),
goodsId char(8) references goods(goodsId),
nums number(2) check (nums  between 1 and 30));

If you forget to create the necessary constraints in the construction of the table, you can use the alter table command after the construction of the table to table adding constraints. But beware: not null constraints increase, need to use modify, to add other options.

 

 1) Customer trade name can not be empty: alter table goods modify goodsName not null;

 2) the address 'East, Chaoyang, Haidian, West': alter table customer add constraint addresscheck check (address in ( 'sun', 'West'));

 3) identification can not be duplicated: alter table customer add constraint cardunique unique (cardId)

Delete constraints: alter table table name drop constraint constraint name

Drop Primary: alter table table name drop primary key cascade;

Data dictionary views show constraint: user_constraints, user_cons_columns

There is no difference in the definition table level and column level defined, but different ways of writing.

Guess you like

Origin www.cnblogs.com/dangjingwei/p/12121840.html