diff --git "a/34\351\231\210\346\264\213/\347\254\224\350\256\260/0920\346\270\270\346\240\207.md" "b/34\351\231\210\346\264\213/\347\254\224\350\256\260/0920\346\270\270\346\240\207.md" new file mode 100644 index 0000000000000000000000000000000000000000..188e872e5d50d44e254600fa616f51926f00a846 --- /dev/null +++ "b/34\351\231\210\346\264\213/\347\254\224\350\256\260/0920\346\270\270\346\240\207.md" @@ -0,0 +1,140 @@ + + +## 游标 + +#### 一 什么是游标: + +游标(Cursor)它使用户可逐行访问由SQL Server返回的结果集。使用游标(cursor)的一个主要的原因就是把集合操作转换成**单个记录处理方式**。用SQL语言从数据库中检索数据后,结果放在内存的一块区域中,且结果往往是一个含有多个记录的集合。游标机制允许用户在SQL server内逐行地访问这些记录,按照用户自己的意愿来显示和处理这些记录。 + +**二 游标的优点**: + +(1) 允许程序对由查询 select 返回的行集合中的每一行执行相同或不同的操作,而不是对整个行集合执行同一个操作 + +(2)提供对基于游标位置的表中的进行删除和更新能力。 + +(3)游标实际上作为面向集合的数据库管理系统(RDBMS)和面向行的程序设计之间的桥梁,使这两种处理方式通过游戏沟通起来。 + + + +**三 游标分类:** + +(1)静态游标(Static):在操作游标的时候,数据发生变化,游标中数据不变 + +(2)动态游标(Dynamic):在操作游标的时候,数据发生变化,游标中数据改变,默认值。 + +(3)键集驱动游标(KeySet):在操作游标的时候,被标识的列发生改变,游标中数据改变,其他列改变,游标中数据不变。 + + + +#### 四 游标的使用 + + **使用游标的顺序: 声名游标、打开游标、读取数据、关闭游标、删除游标。** + +(1)**创建游标:** + +```sql +--1.创建游标(Scroll代表滚动游标,不加Scroll则是只进的,只能支持fetch next) +declare <游标名> cursor scroll for select stuname from stuinfo +``` + +(2)**打开游标:** + +```sql +open <游标名> +``` + +(3)**关闭游标:** + +```sql +close <游标名> +``` + +(4)**删除游标:** + +```sql +deallocate <游标名> +``` + + + +(5)**提取数据操作:** + +```sql +fetch first from <游标名> --结果集的第一行 +fetch last from <游标名> --最后一行 +fetch absolute 1 from <游标名> --从游标的第一行开始数,第n行。 +fetch relative 3 from <游标名> --从当前位置数,第n行。 +fetch next from <游标名> --当前位置的下一行 +fetch prior from <游标名> --当前位置的上一行 +``` + + + +**提取数据给变量以供它用(取出第3行学生姓名,查询该学生详细信息):** + +```sql +declare @vari varchar(20) +fetch absolute 3 from <游标名> into @vari +select * from StuInfo where stuName = @vari +``` + +**利用游标提取所有的学生信息:** + +```sql +--方案一: +fetch absolute 1 from <游标名> +while @@FETCH_STATUS = 0 --@@FETCH_STATUS=0,提取成功,-1提取失败,-2行不存在 + begin + fetch next from <游标名> + end + +--方案二: +declare @myvar varchar(20) +fetch first from <游标名> into @myvar +while @@FETCH_STATUS = 0 + begin + print '提取成功'+@myvar + fetch next from <游标名> into @myvar + end +``` + +**利用游标修改和删除数据:** + +```sql +--更新语法: +-- fetch absolute 3 from <游标名> +-- update 语句 where Current of <游标名> + + +--练习1:修改周飘的班级id为1 + +--练习2:使用删除姓名为曾鹏的个人信息 + +``` + +**创建游标指向某行多列数据,并循环显示数据:** + +```sql +--此处如果指向所有数据,可以将for后面的语句修改成select * from stuinfo +declare <游标名> cursor scroll +declare mycursor cursor scroll for select stuname,StuSex,ClassID from stuinfo + +open <游标名> + +declare @name varchar(20) +declare @sex varchar(2) +declare @cid int +fetch first from mycursor into @name,@sex,@cid +while @@FETCH_STATUS=0 +fetch next from <游标名> into into @name,@sex,@cid + +while @@FETCH_STATUS = 0 --@@FETCH_STATUS=0,提取成功,-1提取失败,-2行不存在 + begin + print '提取成功' + fetch next from CURSORMember into@into @name,@sex,@cid + end +close <游标名> +``` + + +