SQLServer 游标的创建和使用基本步骤

  -- 假设Employees表有两列:Name(名字)和Position(职位)

  -- 步骤1: 声明游标

  DECLARE cur_employee CURSOR FOR

  SELECT Name, Position FROM Employees;

  -- 步骤2: 打开游标

  OPEN cur_employee;

  -- 声明变量以存储提取的数据

  DECLARE @EmployeeName VARCHAR(100);

  DECLARE @EmployeePosition VARCHAR(100);

  -- 步骤3 & 4: 提取数据并处理

  FETCH NEXT FROM cur_employee INTO @EmployeeName, @EmployeePosition;

  WHILE @@FETCH_STATUS = 0

  BEGIN

  PRINT 'Name: ' + @EmployeeName + ', Position: ' + @EmployeePosition;

  FETCH NEXT FROM cur_employee INTO @EmployeeName, @EmployeePosition;

  END

  -- 步骤5: 关闭游标

  CLOSE cur_employee;

  -- 步骤6: 释放游标

  DEALLOCATE cur_employee;