1、索引
数据表中数据和相应存储位置的列表
特点:提高在表或视图中查找数据的速度
分类: ①聚集索引
表中数据行的物理存储顺序与索引顺序完全相同
/*--聚集索引--*/
--主键会自动生成同名聚集索引,不能再创建
②非聚集索引
表中数据行的物理存储顺序与索引顺序完全相同
使用情况:某个字段的数据唯一性较高
查询所得的数据量较少
已经包含聚集索引
/*--非聚集索引--*/
--基本语法
--CREATE [ UNIQUE ] [ CLUSTERED | NONCLUSTERED ]
--INDEX index_name
--ON table_name (column_name)
--[WITH FILLFACTOR=x] 填充因子:指定一个0~100之间的值,表示索引页填充的百分比
--创建索引
--如果存在该索引,先将其删除掉
IF exists(SELECT * FROM sys.indexes WHERE name = 'IX_score')
DROP INDEX stuMarks.IX_score
--对成绩字段创建非聚集索引,填充因子30%
CREATE NONCLUSTERED INDEX IX_score ON stuMarks(score) WITH FILLFACTOR= 30
GO
--使用索引
--指定按索引查询
SELECT * FROM stuMarks WITH(INDEX = IX_score)
WHERE score between 60 and 90
例子:
if exists(select*from sys.indexes where name='IX_stuinfo_stuname')
drop index stuinfo.IX_stuinfo_stuname
create unique NONCLUSTERED
index IX_stuinfo_stuname
on dbo.stuinfo(stuname)
select*from StuInfo with(index=IX_stuinfo_stuname)
where stuName='张三'
create NONCLUSTERED
index IX_StuMarks_score
on dbo.stuMarks(score)
select*from StuMarks with(index=IX_StuMarks_score)
2、视图
①视图是虚拟表
②视图不存放数据
--基本语法
--CREATE VIEW view_name [(列名...)]
--AS
--<SELECT语句>
--创建视图
--如果存在该视图,先将其删除掉
IF EXISTS ( SELECT * FROM sys.views WHERE NAME = 'view_stuInfo_stuMarks')
DROP VIEW view_stuInfo_stuMarks
GO
--创建名为view_stuInfo_stuMarks的视图
CREATE VIEW view_stuInfo_stuMarks(学号,姓名,成绩)
AS
SELECT stuName,stuInfo.StuID,score FROM stuInfo LEFT JOIN stuMarks
ON stuInfo.StuID = stuMarks.StuID
GO
--使用视图
select * from view_stuInfo_stuMarks
--视图加密
--查看所有视图信息
select * from information_schema.views;
EXEC sp_helptext 'view_stuInfo_stuMarks'
--加密试图
IF EXISTS ( SELECT * FROM sys.views WHERE NAME = 'view_stuInfo_stuMarks')
DROP VIEW view_stuInfo_stuMarks
GO
CREATE VIEW view_stuInfo_stuMarks(学号,姓名,成绩)
WITH encryption
AS
SELECT stuName,stuInfo.StuID,score FROM stuInfo LEFT JOIN stuMarks
ON stuInfo.StuID=stuMarks.StuID
GO
例子:
--删除视图
if exists (select*from sys.views where name='stu_marks') drop view stu_marks
go
--对 排名 学号 姓名 总成绩进行排名
--创建视图
create view stu_marks
with encryption --对视图加密
as
select DENSE_RANK () over(order by sum(score) desc) '排名',
StuInfo.stuid '学号',stuname '姓名',stusex '性别',sum(score) '总分'
from StuInfo,StuMarks
where StuInfo.stuid=StuMarks.stuid
group by stuinfo.stuid,stuName,stusex
go
--查询视图
select *from stu_marks where 姓名='张三'