游标

一、游标概念: 将某一结果集作为一个集合处理,且每次处理数据集的一行或一行的某些字段。

     建立游标结构如下:

   1. 定义游标,将游标与Transact-SQL语句的结果集相关联。

      Declare @bookid int, @bname varchar(50),@bindex int

      Declare book_cursor  cursor for

            Select bookid,bookname,bookIndex from Bas_bookList

    

   2.  执行Transact-SQL语句数据集填充游标即打开游标

Open book_cursor

 

   3.  从游标中检索到第一行,并提取第一行或第一行的某些字段。

       Fetch  next  from book_cursor  into @bookid,@bname,@bindex

 

   4.  根据需要对当前行进行操作

   @@Fetch_status包括三种状态 0,-1,-2。以此来判断游标执行是否正确。

    0则游标执行正确,-1 游标中出现错误,-2 找到空行

        While @@fetch_status=0

        Begin

           Delete update insert 等等

Fetch next  from book_cursor  into @bookid,@bname,@bindex  选取下一行数据

        End

 

  4.  关闭游标

    Close book_cursor

        Deallocate book_cursor

posted @ 2010-03-31 22:44  YoungPay  阅读(116)  评论(0编辑  收藏  举报