数据库中定义表和建立完整性代码

本文详细介绍了使用SQL语句创建数据库表的过程,并为不同表定义了各种完整性约束条件,包括主键、外键、检查约束等。通过具体示例展示了如何确保数据的一致性和准确性。
--***************************************实验一******************************************
--**********************************建立表和定义完整性约束**************************
create database js
use  js
drop table 院系
create table 院系( 编号     smallint   Primary key,
                   名称     char(20) not null,
                   负责人   char(10),
                   办公地点 char(20),
                   constraint uniquea unique (名称)
                   )


create table 学生( 学号 char(8) Primary key,
                    院系 smallint,
                    姓名 char(10),
                    性别 char(2) check(性别 in('男','女')),
                    生源 char(6),  
                    状态 char(4) check(状态 in('正常','留级','休学','退学')))




drop table 教师
create table 教师( 教师编号 char(8) Primary key,
                   院系 smallint  foreign key references 院系(编号),
                   姓名 char(10),
                   性别 char(2) check(性别 in('男','女')),
                   职称 char(6) check(职称 in('教授','副教授','讲师','助教')),
                   专业 char(10))
 
drop table 课程           
create table 课程( 课程编号 char(8)Primary key,
                   课程名称 char(20)not null,
                   责任教师 char(8)foreign key references 教师(教师编号),
                   学时 smallint not null,
                   课程性质 char(10) check(课程性质 in('公共基础','专业基础','专业选修','任意选修')))
              
             
drop table 选课
create table 选课( 学号 char(8)foreign key references 学生(学号) on delete cascade,
                   课程编号 char(8) foreign key references 课程(课程编号),
                   成绩 smallint  check(成绩>=0 and 成绩<=100)default null,
                   primary key(学号,课程编号))




--实验要求
alter table 学生 add 平均成绩 smallint default null


alter table 课程 add constraint  chk_xueshi check(学时%8=0) 
alter table 课程  alter column 学时 smallint not null


alter table 院系 drop  constraint uniquea
alter table 院系 alter column 名称 varchar(30)
alter table 院系 add  constraint uniquea unique(名称)


alter table 教师 add 工资 numeric(5,2)
   
   









评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值