数据库数据表的创建和插入

 一、创建数据库和数据表

 create database和 create table分别对应创建数据库和数据表

not null 为非空约束,primary key是主键约束(可以出现null,但只能出现一次),check约束用来检查字段允许范围(判断相等用单等号) 

定义foreign key约束的语法:constraint  <约束名> foreign key reference <主表名>(<列名>, [{, 列名}])

当一个表需要用多个列作为主键时,参照stu_work中末尾的语句

date为日期类型,不包括时间,datetime是日期时间

create database SCW

use SCW
go

--学生表:学号、姓名、性别、专业班级、生日、电话
create table stu
(
	number char(4) not null primary key,
	name nvarchar(6) not null,
	gender nchar(1) not null check (gender='男' or gender='女'),
	class nvarchar(10) not null,
	birth date not null,
	phone char(11),
)

--课程表:课程号、课程名、学分、学时、教师
create table course
(
	c_No char(4) not null primary key,
	c_Name nvarchar(15) not null,
	credit float not null,
	period int not null,
	teacher nvarchar(6) not null,
)

--学生作业表:课程号、学号、作业一成绩、作业二成绩、作业三成绩
create table stu_work
(
	c_No char(4) not null constraint c_fore foreign key references course(c_No),
	stu_No char(4) not null constraint stu_fore foreign key references stu(number),
	w_one tinyint constraint a1 check(w_one<=100 and w_one >= 0),
	w_two tinyint constraint a2 check(w_two<=100 and w_two >= 0),
	w_three tinyint constraint a3 check(w_three<=100 and w_three >= 0),
	constraint sw_prim primary key(c_No, stu_No)
)

二、向数据表中插入数据

插入语句:insert into <表名>  values (<一行的信息>)[{, [一行的信息]}]

空值用null 

字符型用单引号

date用  ‘xxxx-xx-xx’  表示

use SCW
go

insert into stu values
('0433', '张艳', '女','生物04', '1986-9-13', null),
('0496', '李越', '男', '电子04', '1984-2-23', '1381290xxxx'),
('0529', '赵欣', '男', '会计05', '1984-1-27', '1350222xxxx'),
('0531', '张志国', '男', '生物05', '1986-9-10', '1331256xxxx'),
('0538', '于兰兰', '女', '生物05', '1984-2-20', '1331200xxxx'),
('0591', '王丽丽', '女', '电子05', '1984-3-20', '1332080xxxx'),
('0592', '王海强', '男', '电子05', '1986-11-1', null)

insert into course values
('K001', '计算机图形学', 2.5, 40, '胡晶晶'),
('K002', '计算机应用基础', 3, 48, '任泉'),
('K006', '数据结构', 4, 64, '马跃先'),
('M001', '政治经济学', 4, 64, '孔繁新'),
('S001', '高等数学', 3, 48, '赵晓尘')

insert into stu_work values
('K001', '0433', 60, 75, 75),
('K001', '0529', 70, 70, 60),
('K001', '0531', 70, 80, 80),
('K001', '0591', 80, 90, 90),
('K002', '0496', 80, 80, 90),
('K002', '0529', 70, 70, 85),
('K002', '0531', 80, 80, 80),
('K002', '0538', 65, 75, 85),
('K002', '0592', 75, 85, 90),
('K006', '0531', 80, 80, 90),
('K006', '0591', 80, 80, 80),
('M001', '0496', 70, 70, 80),
('M001', '0591', 65, 75, 75),
('S001', '0531', 80, 80, 80),
('S001', '0538', 60, null, 80)
发布了41 篇原创文章 · 获赞 2 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/dzydzy7/article/details/102632467