您好,欢迎访问一九零五行业门户网

游标cursor

sql server 用于处理数据集合。但很多时候,只需要处理一行数据。游标功能可以使我们获取一个数据行集,然后一次处理一行数据。 游标有5个组成部分。declare用于定义一个select语句,该语句生成游标中数据行。open使select语句执行,并将结果导入内存结构中
sql server 用于处理数据集合。但很多时候,只需要处理一行数据。游标功能可以使我们获取一个数据行集,然后一次处理一行数据。
游标有5个组成部分。declare用于定义一个select语句,该语句生成游标中数据行。open使select语句执行,并将结果导入内存结构中。fetch用于从游标中一次获取一行。close则用来关闭游标操作。deallocate用于删除游标,然后重新分配之前存储游标结果集非让内存结构。
(notice:如果写的游标在来自游标中每一行上的操作都相同,建议使用更高效的基于数据集的操作。)
声明游标的通用语法格式如下:
declare cursor_name cursor [ local | remote ] [ static| keyset | dynamic | fast_forward ] [ read_only | scroll_locks | optimistic ] [type_warning] for select_statement
接下来的语句展示了声明相同游标的三种不同的方法: declare curproducts cursor fast_forward for select productid, productname, listprice from products.product go
declare curproducts cursor read_only for select productid, productname, listprice from products.product go
declare curproducts cursor for select productid, productname, listprice from products.product for read only go
一旦游标被声明,就可以发布open命令,就可以发布open命令以执行select语句。 open curproducts
然后就可以用fetch语句从游标中的行获取数据。首次执行fetch命令时,指针位于游标结果集的第一行数据处,再执行一次,指针边在游标中前进一行,直至超出游标结果集的范围。每次执行fetch语句还会在全局变量@@fetch_status中放置一个值。可以使用while循环来遍历游标,循环获取游标中的行。只要@@fetch_status为0,都可以使用while循环。 declare @productid int, @productname varchar(50), @listprice money declare curproducts cursor for select productid,productname,listprice from products.product for read only open curproducts fetch curproducts into @productid,@productname,@listprice while @@fetch_status = 0 begin select @productid,@productname,@listprice fetch curproducts into @productid,@productname,@listprice end close curproducts deallocate curproducts
其它类似信息

推荐信息