oracle中constraints,Oracle对表的基本操作(二)- 约束(Constraints )

在这里,总结一下,对约束的操作,Constraints,有5种类型:

Check

Not NULL

Primary key

Unique

Foreign Key

1. Check

确保指定列中的值符合一定条件。check约束可以涉及该行的同属于check约束的其他数据列,但是不能涉及其他行或者其他表。

单一的数据列可以有多个check保护,一个check约束可以保护多个数据列。

可以在create table时创建check约束,也可以在alter table时修改表的约束。

其语句格式为 constraint [约束名] check(codition). 约束名不是必须的,但是最好有一个名字。

create table t_ygy_demo_editor

(

editor_key varchar2(9) not null,

editor_last_name varchar2(40),

editor_first_name varchar2(30) not null,

editor_hire_date date,

editor_active char(1)

constraint active_ck check (editor_active in ('Y','N'))

);

alter table 表名 add constraint chka1 check(a1 in (1,0));

alter table 表名 disable/enable/drop constraint chka1; 示例:

ALTER TABLE

T_YGY_DEMO_A

ADD CONSTRAINT C_2 CHECK (A_ID > 5);

2. Not Null

它作用在单一数据列上,保证数据列必须要有数据值。当not null是在alter table时才添加上时,写法有所不同:

create table 表名

(

a1 int not null,

a2 int

)

alter table 表名 modify a2 not null

3. Primary Key

是表中的一列或者多列,决定表中每个行的唯一性,主键列必须是not null。如果是复合主键,要放入括号中。比如:

create table 表名

(

stuid int,

courseid int,

primary key(列名1, 列名2, ......),

score float

)

alter table 表名 add constraint 主键名 primary key (列名s)

alter table 表名 drop/disable/enable primary key(或者用名字);

4. Unique

保证那些具有惟一性但又不是主键的一部分列的唯一性。可以保护多个列,唯一性约束与表一起创建,可以用alter table语句修改它:

create table 表名

( a1 int unique,

a2 int)

alter table 表名 add constraint 约束名 unique(列名s)

alter table 表名 disable /enable/ drop constraint 约束名 不能删除带有外键指向的表的唯一性约束,除非先禁用或者删除了外键。删除或者禁用唯一性约束通常会同时删除相关联的唯一索引,降低性能,

要避免这种情况,可以在唯一性约束保护的数据列上先创建非唯一性索引,再添加唯一性约束。

5. Foreign Key

create table a create table b

( (

a1 int primary key, b1 int primary key,

a2 int not null, b2 int not null,

a3 int unique )

)

create table c

(

ca int,

cb int,

primary key(ca, cb),

constraint 外键名1 foreignkey(本表列1) references 其他表(其他表中对应列),

constraint 外键名2 foreignkey(本表列2) references 其他表(其他表中对应列)

)

alter table 表名 add constraint 外键名 foreign key(本表列名) references 其他表(其他表中对应列);

alter table 表名 disable/enable/drop constraint 外键名

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值