sql数据库基础实例

操作环境 win10+sql2016

目的 加深对SQL语句的理解和方便以后的查询、复习

例1 创建数据库

在D盘的data文件夹下建立名为高校图书管理的数据库,主数据文件为高校图书管理 _data,初始容量为10MB,最大容量为50MB,增幅为10MB。日志文件为高校图书管理 _log,初始容量为5MB,最大容量为20MB,增幅为5MB。

create database 高校图书管理 on primary ( name=高校图书管理_data, filename="D:\data\高校图书管理_data.mdf", size=10MB, maxsize=50MB, filegrowth=10% ) log on ( name=高校图书管理_log, filename="D:\data\高校图书管理_log.ldf", size=5MB, maxsize=20MB, filegrowth=5% ) GO

例2 创建基本表

为高校图书管理数据库,创建读者类别表、读者表、图书表、借阅表。要求如下:

  • 读者类别包含的字段有类别编号、类别名称、可借阅天数、可借阅数量、超期罚款额,其中类别编号为主键,类别名称、可借阅天数、可借阅数量、超期罚款额不能为空。
  • 读者表包含的字段有读者卡号、姓名、性别、单位、办卡日期、卡状态、类别编号,其中卡号为主键,姓名、性别、单位、办卡日期、卡状态、类别编号不能为空。
  • 图书表包含的字段有图书编号、书名、类名、作者、出版社、出版日期、单价、库存数量,其中图书编号为主键,书名、类名、作者、出版社、出版日期、单价、库存数量不能为空。
  • 借阅表包含的字段有读者卡号、图书编号、借书日期、还书日期,其中读者卡号和图书编号为主键,且分别参照读者表的读者卡号和图书表的图书编号,借书日期、还书日期不能为空。
use 高校图书管理
go
create table 读者类别( 类别编号 char(2) primary key, 类别名称 char(10) not null, 可借阅天数 tinyint not null, 可借阅数量 tinyint not null, 超期罚款额 smallmoney not null ) go create table 读者( 读者卡号 char(10) primary key, 姓名 char(16) not null, 性别 char(1) not null default '男', 单位 char(30) not null, 办卡日期 date not null, 卡状态 char(5) not null, 类别编号 char(2), constraint c1 check(性别 in('男','女')), constraint c2 foreign key(类别编号) references 读者类别(类别编号) ) go create table 图书( 图书编号 char(8) primary key, 书名 char(40) not null, 类名 char(16) not null, 作者 char(16) not null, 出版社 char(20) not null, 出版日期 date, 单价 smallmoney not null, 库存数量 tinyint not null ) go create table 借阅( 读者卡号 char(10), 图书编号 char(8), 借书日期 date not null, 还书日期 date, constraint c3 primary key(读者卡号,图书编号), constraint c4 foreign key(读者卡号) references 读者(读者卡号), constraint c5 foreign key(图书编号) references 图书(图书编号) ) go

例3 修改基本表

  • 为高校图书管理数据库的读者表增加新的整型id,该列作为每行数据的标识,并且自动增加,初始值为1.在读者姓名一列增加唯一性约束约束名为unique_dzxm。
Use 高校图书管理
go
alter table 读者 add id int identity(1,1) go alter table 读者 with nocheck add constraint unique_dzxm unique(姓名) go
  • 假设读者类别表中未定义主键,将读者类别中的类型编号定义为主键
alter table 读者类别 add primary key(类别编号)
  • 将读者表新增的id列删除
alter table 读者 drop column id go

若一列上有约束或默认值,则无法删除,必须先删除约束 ,例如姓名

alter table 读者 drop constraint unique_dzxm go alter table 读者 drop column 姓名 go

例4 索引

  • 在图书表的书名列上,创建一个名称为idx_sm的唯一索引,并依据书名字段进行升序排序
Use 高校图书管理
go
alter table 读者 add id int identity(1,1) go alter table 读者 with nocheck add constraint unique_dzxm unique(姓名) go
  • 在读者表的姓名和性别上,创建一个idx_xmxb的唯一非聚集复合索引,并根据姓名升序,性别降序进行排序
create unique nonclustered index idx_xmxb on 读者(姓名,性别desc)
    原文作者:SQL
    原文地址: https://blog.csdn.net/qq_26450765/article/details/79380617
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞