SQL 游标

游标详解之基本 语法
作者:佚名转自:http://www.pushad.com点击:208发布日期:2007-7-4

要想明白什么是游标就不能不从游标的定义来谈了,看看游标的TSQL定义语法


DECLARE cursor_name CURSOR
[ LOCAL | GLOBAL ]
[ FORWARD_ONLY | SCROLL ]
[ STATIC | KEYSET | DYNAMIC | FAST_FORWARD ]
[ READ_ONLY | SCROLL_LOCKS | OPTIMISTIC ]
[ TYPE_WARNING ]
FOR select_statement
[ FOR UPDATE [ OF column_name [ ,...n ] ] ]

SQL游标的简单使用

Posted on 2007-06-29 13:46 williambirkin 阅读(18) 评论(0) 编辑 收藏 所属分类: [J] SQL Server <!-- <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/"> <rdf:Description rdf:about="http://www.cnblogs.com/williambirkin/archive/2007/06/29/800114.html" dc:identifier="http://www.cnblogs.com/williambirkin/archive/2007/06/29/800114.html" dc:title="SQL游标的简单使用" trackback:ping="http://www.cnblogs.com/williambirkin/services/trackbacks/800114.aspx" /> </rdf:RDF> -->
CREATE PROCEDURE [ dbo ] . [ pro_CURSOR ]
AS
BEGIN

-- 声明一个游标
DECLARE MyCURSOR CURSOR FOR
SELECT userid,depid FROM users

-- 打开游标
open MyCURSOR

-- 声明两个变量
declare @userid varchar ( 50 )
declare @depid varchar ( 50 )

-- 循环移动
fetch next from MyCURSOR into @userid , @depid
while ( @@fetch_status = 0 )
begin
update users set description = ( select dep_des from department where depid = @depid )
where userid = @userid
fetch next from MyCURSOR into @userid , @depid
end

close MyCURSOR
deallocate MyCURSOR

END


再来看一个使用游标的例子,注意后面的注释

DECLARE myCur CURSOR
-- 定义一个名称为myCur的游标对象

FOR SELECT [name] FROM Products
-- 定义了这个游标的功能

OPEN myCur
-- 打开游标

FETCH NEXT FROM myCur INTO @username
-- 检索结果行并赋值到@username

WHILE @@FETCH_STATUS = 0
-- 返回最后被执行的游标的状态(0为成功)

FETCH NEXT FROM myCur
-- 检索下一条结果行(循环)

CLOSE myCur
-- 关闭游标

DEALLOCATE myCur
-- 销毁游标对象

这是一个简单语法结构的游标使用,很明显的看出游标具有循环的某些特点,@@FETCH_STATUS 是循环条件,当它不为0时,说明结果集已经到达最后一行或者结果集不存在,那么就跳初循环直接CLOSE掉myCur这个游标对象。那么现在就很好明白游标是什么了。游标其实就是循环提取满足SELECT_STATEMENT结果集的一个数据库对象。虽然游标看似简单,当要恰如其分的使用它还需要多多的练习和总结

你可能感兴趣的:(html,数据结构,sql,sql,xml,server)