SQL server中使用视图,索引,游标

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_36027342/article/details/89842537

一.视图(view)

视图其实就是一个虚表,是从一个或多个表中使用select语句导出的虚表,用来导出的表称为基本表;对视图的操作会影响到基本表

为什么要使用视图?

  1. 为用户集中数据,简化用户的数据查询和处理
  2. 保证数据的逻辑独立性
  3. 重新定制数据,使数据便于分享
  4. 数据保密,增加了安全性

注意:

  • 不是所有视图都可以更新(因其包含派生域或常量域);
  • 定义视图的查询不可以包含order by,compute,compute by子句或into关键字
  • with check option:强制视图上执行的所有数据修改语句都必须符合由select_statement设置的准

示例:

create view view_Student
as select *
     from Student
     where Sdept='cs'
    with check option;

二.索引(index)

索引就相当于我们平常要看书,或者图书馆要搜索某本书的一个目录

  • 聚集索引:对表和视图进行物理排序,只能有一个
  • 非聚集索引:最多250个

三.游标

总是与一条select语句相关联,游标由与之相关联的select语句得到的结果集和指向结果集中记录位置的指针构成;

可逐行读取游标中的数据

游标使用:

--声明declare 游标名 cursor for select 语句

--打开open 游标名

--读取fetch first|last|absolute n|relative n|prior|next from 游标名into #变量1..

--关闭close 游标名

--释放deallocate 游标名

代码示例:

declare cur_Stu cursor for select Sno,Sname,Sage from Student
open cur_Stu
declare @Sno char(9),@Sname varchar(20),@Sage int
fetch next from cur_Stu into  @Sno,@Sname,@Sage
while @@fetch_status=0
begin
	print '学号:'+@Sno+'  姓名:'+@Sname+'   年龄:'+cast(@Sage as char(2))
	fetch next from cur_Stu into  @Sno,@Sname,@Sage
end
close cur_Stu

猜你喜欢

转载自blog.csdn.net/weixin_36027342/article/details/89842537