今天看sql报表的时候,看到数据库的sql语句,有很长的一段游标的语句,
自己对游标不是很熟悉,借此机会也记个笔记。
https://www.cnblogs.com/kingteach/p/3801054.html
游标知识点1 游标原理及为什么使用游标
declare @UNum intdeclare @UGraduate varchar(100)--他的意思就是先从某个表中,获取一些数据,放到他自己的游标(Cursor)里,这时候自定义的CursorDemo 他就是一个数据集合啦
--然后在begin里面 对一些表进行更改;begin就好比你进入了一个循环:declare CursorDemo cursor for select UNum,UGraduate from UserInfoopen CursorDemo--这个是开始CursorDemo里的数据,一行一行的赋给这2个自定义的变量fetch next from CursorDemo into @UNum,@UGraduate
while(@@fetch_status=0)如果不加会显示只能执行第一条的数据,加过之后才会把所有符合的数据加上ojbk
begin update UserInfo set UGraduate=@UGraduate+'Ojbk'where UNum=@UNum--这个id 是你要更改的id --@id是你自定义里面游标里的id--每次循环的时候,这俩个匹配上了,那么更改的表里的数据,也就改掉了fetch next from CursorDemo into @UNum,@UGraduateendclose CursorDemodeallocate CursorDemo
-----------------------------------------------------------------------------declare m_cursor cursor scroll for select Address,PeopleId from PeopleDetail open m_cursor declare @Address varchar (50), @PeopleId int fetch next from m_cursor into @Address,@PeopleId while @@FETCH_STATUS=0 begin print @Address + convert ( varchar (3), @PeopleId) fetch next from m_cursor into @Address,@PeopleId end close m_cursor deallocate m_cursor 释放游标,也叫删除游标 ------------------------------------------------------------ 关于释放游标: 1.创建了游标,他就存在于内存之中;创建后就要释放,一个好的程序员应该养成这样的习惯,不要以为反正系统会给释放,结果谁都没释放,后果是,或者它无谓地占着空间,或者会出点什么溢出之类的事情,特别是那些在循环中创建的东西,一定得在循环中用完后释放. 2.记住一点:创建了不使用就把它给释放。这个习惯很重要 -----------------------------------------------------------------------------------------------------------------------------------------------------------------declare my_cursor cursor scroll dynamic /*scroll表示可随意移动游标指针(否则只能向前),dynamic表示可以读写游标(否则游标只读)*/forselect SONumber from tms_SOHead where CreateTime>'2018-03-07'
open my_cursordeclare @name sysnamefetch next from my_cursor into @name--把每一行的SONumber都赋给@name--/* 读取第1行数据*/ while(@@fetch_status=0)beginprint 'UserName: ' + @name--fetch next from my_cursorfetch next from my_cursor into @name--/* 在循环体内将读取其余行数据 */ 在begin外那一个读取进到循环体内,末尾的那个继续当做“引子”进行循环,直到读取完end
--fetch first from my_cursor into @nameprint @name--查询数据的最后一个/* update 个人资料 set 姓名='zzg' where current of my_cursor *//* delete from 个人资料 where current of my_cursor */close my_cursordeallocate my_cursor
转载于:https://www.cnblogs.com/ZkbFighting/p/8465967.html
