数据库中常用的对字段的操作

1.增加字段

Alter Table 表名 Add 字段名称  字段类型
alter table course add tid int;   --在课程表中增加教师编号tid字段
Alter Table 表名 Add (字段名称  字段类型,字段名称  字段类型.....);  --增加多个字段

2.修改字段

(1)修改字段的名称

Alter Table 表名 rename  column 原字段名  to 新字段名;
alter table stu rename column sid to zid;  --将学生表中的sid字段重命名为zid

(2)修改字段的类型和长度

Alter Table 表名  modify (字段名称  (新的)字段类型或者新的长度);
alter table sc add mim int;  --在成绩表中增加一列mim
alter table sc modify(mim varchar(10));   --修改mim字段的数据类型
alter table sc modify(mim varchar(30));  --修改mim字段的长度,当此列有数据时,不能将字段的长度减小,只能增加长度

3.删除字段

alter table 表名 drop column 字段名;
alter table sc drop column mim;   --删除成绩表中的字段mim

4.添加约束

六大约束
 1.—-主键约束(Primay Key Coustraint) 唯一性,非空性
 2.—-唯一约束 (Unique Counstraint)唯一性,可以空,但只能有一个
 3.—-检查约束 (Check Counstraint) 对该列数据的范围、格式的限制(如:年龄、性别等)
 4.—-默认约束 (Default Counstraint) 该数据的默认值
 5.—-外键约束 (Foreign Key Counstraint) 需要建立两表间的关系并引用主表的列
 6.--非空约束(not null Constraint) 字段内容不能为空

(1)在建表时添加约束

create table stu( 
id number, 
 --学生姓名,不能为空,不能重复 
name varchar2(20) not null unique, 
 --学生姓名只能是male或female 
sex varchar2(6) not null check(sex='male' or sex='female'),
 --学生年龄只能在18到60之间 
age number check(age >18 and age <60), 
 --邮箱可以不填写,填写的话不能相同 
email varchar2(30) unique, 
address varchar2(30) default '湖南怀化', 
--外键约束 
cid int not null references c(cid)  
);

(2)创建字段约束

a.创建主键约束

alter table 表名
add constraints 约束名 primary key(字段名);
--为表增加主键约束 
alter table stu
add constraints pk_id primary key(id);

b.创建外键约束

alter table 表名
add constraints 约束名 foreign key(字段名) references 引用表的表名(相应的字段名);
alter table c add constraint fk_tid foreign key(tid) references teacher(tid)  --在课程表中创建外键tid

c.创建唯一约束

alter table 表名
add constraints 约束名 unique(字段名);
alter table stu 
add constraints name_unique unique(name);    --姓名不能重复

d.添加检查约束

alter table 表名 
add constraints 约束名 check(检查条件);
--添加检查约束 
alter table stu
add constraints check_age check(che_age>18 and che_age<60);

e.创建非空约束

alter table 表名 modify 字段名 not null;
alter table stu modify name not null;

f.创建默认约束

alter table 表名 modify 字段名 default 默认值;
alter table stu modify address default '湖南怀化'

(2)删除约束

--删除主键约束 
alter table 表名 
drop constraints 约束名;
--删除主键约束 
alter table stu
drop constraints age_check;

(3)禁用约束

--禁用约束 
alter table 表名 disable constraints 约束名;
--禁用约束 
alter table stu disable constraints age_check;
(4)启用约束
--启用约束 
alter table 表名 enable constraints 约束名;
--起用约束 
alter table stu enable constraints age_check;













评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值