create DataBase db_HXX
on
(
name=HXX_Data,
filename='D:\Data\HXX_Data.mdf',size=5,
maxsize=15,
filegrowth=2
)
log on
(
name=HXX_LOG,
filename='D;\Data\HXX_LOG.ldf',size=3,
maxsize=10,
fileGrowth=1
)
unlimited 无设置
create table Student
(
sno char(10) primary key,
sfzh char(18) unique,
cname varchar(16) not null,
sex char(2) check(sex='男' or sex='女'),
dept varchar(30) default'软件学院',
birthday datetime,
score float check(score between 0 and 100),
polity char(8) check(polity='党员' or polity='团员' or polity='群众')
)
复合主键: consteaint pk_snocname primary key(sno,cname);
外键:consteaint pk_sc foreign key(sno) references db_student.dbo.tb_student(sno) 设置外键时必须有参考的主键
查询条件 | 谓词 |
---|---|
比较(比较运算符) | >,<,=,>=,<=,!=,<>不等于,!>,!< |
确定范围 | between a and b ,not between a and b |
确定集合 | in, not in 确定集合 |
字符匹配 | like, not like 字符匹配 |
空值 | is null , is not null |
多重条件(逻辑谓词) | and , or |
字符串中可以含有的通配符
通配符 | 功能 | 实例 |
---|---|---|
% | 代表0或多个字符 | ‘强%’强后可接任意字符串 |
_ (下划线) | 代表一个字符 | ‘强_ _’后面只有俩个字符 |
[ ] | 表示在某一范围的字符 | [0~9]在0~9之间 |
[^ ] | 表示不再某一范围的字符 | [^0~9] 不再0~9之间 |
常用的库函数及功能
函数名称 | 功能 |
---|---|
AVG | 按列计算平均值 |
SUM | 按列求和 |
MAX | 求一列中的最大值 |
MIN | 求一列中的最小值 |
COUNT | 按列统计个数 |
use db_student17
select * from tb_student where SUBSTRING(sno,7,2) in('14','15')
select sno,sn,sex,SUBSTRING(sno,7,2) as 班级,year(GETDATE())-year(birthday) as 年龄 from tb_student where SUBSTRING(sno,7,2) in('14') order by 年龄 asc
use db_student17
select count(*)from tb_student
use db_student17
select sno,count(*)from tb_score
group by sno
use db_Book
select CBS,COUNT(CBS)as 存书数量 from tb_BookInfo
group by CBS having COUNT(CBS)>100
求各个班有多少人,降序排序
use db_student17
select SUBSTRING(sno,5,4) as 班级 ,count(sno) as 人数 from tb_student
group by SUBSTRING(sno,5,4)
order by 人数 desc
select sno,sc.cno,cn,score
from tb_course c join tb_score sc
on c.cno = sc.cno
select sno,sc.cno,cn,score
from tb_course c,tb_score sc
where c.cno = sc.cno
select s.sno,sn,cn,score
from tb_student s,tb_score sc,tb_course c
where s.sno = sc.sno and sc.cno = c.cno
left outer join *左外部连接
right outer join *右外部链接
full outer join *完全外部链接
use db_student17
select sno,dept
from tb_student
where dept=(select dept from tb_student where sn=’强’)
例:查询所有年龄大于20岁的同学
use db_student17
select sn from tb_student where YEAR(birthday) in
(select YEAR(birthday) from tb_student where YEAR(birthday)>20)
例:查询1比14班所有学生年龄都大的同学
use db_student17
select sn from tb_student where YEAR(birthday) > all
(select YEAR(birthday) from tb_student where SUBSTRING(sno,5,4)=0114)
创建视图:
create view 视图名(字段可有可无)
as
select(查询语句)
修改视图:
alter view 视图名(字段可有可无)
as
select(查询语句)
删除视图:
drop view 视图名
查询视图:
和查询一样
添加(insert into)
insert into 视图名(字段)
value(字段值)
修改(update set)
update 视图名
set 字段=值
where 条件
删除(delete)
delete from 视图名
where 条件
创建索引
create <> index 索引名 on 表(列)
查看索引
sp_helpindex t_course
删除索引
drop index t_course.qwe