1.使用 create database 语句可以创建数据库,使用 drop database 语句可以删除数据库 2.使用 create table 语句可以创建数据库的表结构,使用 drop table 语句可以删除表结构 3.使用alter table 语句可以创建一下约束: * 主键约束 (primary key constraint):要求主键列数据唯一,并且不允许为空 * 非空约束(not null):要求列不能存在空值 * 唯一约束 (unique constraint):要求该列的值必须唯一,允许为空 * 检查约束 (check constraint):某列的取值范围限制,格式限制等 * 默认约束 (default constraint):某列的默认值 * 外键约束 (foreign key constraint):用于在两表之间建立关系,需要指定引用主表的哪一列 4.创建数据库或表时一般需要预先检测是否存在对象,SQL Server中的数据库可以从master系统数据库的sysdatabases表中查询,而一个数据库中的表可以从该数据库的系统表sysobjects中查询 5.数据完整性是指数据的正确性和相容性 6.实体完整性:唯一确定表中一行记录 7.域完整性:表中特定列数据的有效性,以确保不会输入无效的数值 8.引用完整性:插入或删除记录时,维护表之间定义的关系
use master --设置当前数据库为master,以便访问sysdatabase表 go if exists(select * from sysdatabases where name='S2226') drop database S2226 create database S2226 --创建数据库 on primary ( --数据文件 name='S2226_data', --逻辑名称 filename='D:\\S2226_data.mdf', --物理名称 size=5mb, --初始大小 maxsize=100mb, --最大值 filegrowth=15% --增长率 ) log on ( --日志文件 name='S2226_log', filename='D:\\S2226._log.ldf', size=2mb, filegrowth=1mb ) use S2226 create table Student --创建student表 ( studentid int not null, studentname varchar(20) not null, sex bit not null, address nvarchar(50) null, borndate datetime null, class int not null ) create table Grade --创建Grade表 ( studentid int not null, studentname varchar(20) not null, sex bit not null, address nvarchar(50) null, borndate datetime null, class int not null ) --向Grade表中添加数据 insert into dbo.Grade(studentid, studentname, sex, address, borndate, class) values (1,'小小',1,'','',1) insert into dbo.Grade(studentid, studentname, sex, address, borndate, class) values (2,'哈哈',1,'','',2) insert into dbo.Grade(studentid, studentname, sex, address, borndate, class) values (3,'嘿嘿',1,'','',3) --向Student表中添加数据 insert into dbo.Student(studentid, studentname, sex, address, borndate, class) select 1,'哒哒',1,'','',1 union select 2,'嘟嘟',1,'','',2 union select 3,'欧耶',1,'','',3 delete from dbo.Student --删除Student表中的数据 delete from dbo.Grade --删除Grade表中的数据 --主键约束,年级编号 alter table Grade add constraint pk_class primary key (class) --主键约束,学号 alter table Student add constraint pk_studentid primary key (studentid) --唯一约束,姓名 alter table Grade add constraint uq_studentname unique (studentname) --默认约束,默认为'地址不祥' alter table Grade add constraint df_address default ('地址不详') for address --检查约束 alter table Grade add constraint ck_borndate check (borndate>=1980-01-01) --外键约束 alter table Student add constraint fk_studentid foreign key(studentid) references Student(studentid) --删除约束(外键) alter table Student drop constraint fk_studentid --删除表 drop table Student
优化MySchool 第二章:数据库的实现
最新推荐文章于 2019-07-17 22:50:55 发布