一、使用游标的几个步骤

(1)创建游标对象

在SQL Server中创建游标对象使用关键之declare(变量声明)以及curosr(游标)。

declare 
    --创建游标
    cur cursor for select _user,_pwd from userTable;

(2)打开游标对象

游标对象创建之后,必须打开之后才能进行使用,使用关键字open。

    --打开游标
    open cur;

(3)移动游标进行取值

--声明两个变量接收从游标中取出的值
declare
@use varchar(20),@pw varchar(20); --移动游标取值 fetch next from cur into @use,@pw; print(@use); print(@pw);

(4)游标使用完毕之后需要关闭,以及资源的释放,关键字close,deallocate。

    --关闭游标
    close cur;
    deallocate cur;

二、简单举例

使用游标查询userTable中所有的数据,只获取取字段_user,和字段_pwd

表结构如下:

SQLServer游标的简单使用

 

 

 这里会用到游标的状态。

declare 
    --创建游标
    cur cursor for select _user,_pwd from userTable;
declare

    @use varchar(20),@pw varchar(20);
    begin
    --打开游标
    open cur;
    --移动游标取值
    fetch next from cur into @use,@pw;
    --这里对游标的状态进行判断,如果为0,证明游标中有值
    while @@FETCH_STATUS = 0
        begin
            print(@use);
            print(@pw);
            --让游标继续往后移动
            fetch next from cur into @use,@pw
        end
    --关闭游标
    close cur;
    deallocate cur;
    end

 

相关文章:

  • 2022-01-24
  • 2022-12-23
  • 2021-09-16
  • 2021-11-28
  • 2021-09-14
  • 2021-10-17
猜你喜欢
  • 2021-07-25
  • 2021-08-26
  • 2021-11-11
  • 2021-09-20
  • 2021-11-28
  • 2021-10-25
相关资源
相似解决方案