SQLServer存储过程中的游标使用

游标

项目中自动增长的表格的生成涉及到数据库查询结果集的批量操作

检索操作返回一组称为结果集的行。这组返回的行都是与SQL语句相匹配的行(零行或多行)。使用简单的SELECT 语句不能每次一行地处理所有行(相对于成批地处理它们)。

游标(cursor)是一个存储在数据库服务器上的数据库查询,它不是一条SELECT 语句,而是被该语句检索出来的结果集。在存储了游标之后,应用程序可以根据需要滚动或浏览其中的数据。

待查询的数据表

CREATE PROCEDURE find_anpogongkuang 
    --输入参数
    @targetID int,
    --输出参数
    @text varchar(500) output
AS
BEGIN
    --初始化
    SET @text=''
    --定义游标
    declare cursor_test cursor
    for
    --查询出一个结果集,注意,这里的*有几个变量,在下面就要declare几个变量,并且顺序要一一对应
    select * from [dbo].[anpo_gongkuang] where anpo_gongkuang.target_id=@targetID
    --与上面对应
    declare @target_id int,
        @bishop varchar(50),
        @mp varchar(50),
        @qdzj varchar(50),
        @kzbz varchar(50),
        @working_condition_type varchar(50)
    --打开游标
    open cursor_test
        fetch next from cursor_test
        into @target_id,@bishop,@mp,@qdzj,@kzbz,@working_condition_type
        --fetch到数据时进行的操作
        WHILE @@FETCH_STATUS = 0
        begin
            --这里面可以写具体的操作逻辑,例如我这里就是拼接结果赋值给@text
            fetch next from cursor_test
            into @target_id,@bishop,@mp,@qdzj,@kzbz,@working_condition_type
            SET @text=@text+@mp+'+'+@qdzj+'+'+@kzbz+'+'+@working_condition_type
        end
    --关闭游标
    close cursor_test
    --删除游标
    deallocate cursor_test
END
GO

测试

 

 

原文地址:https://www.cnblogs.com/liuliang1999/p/12656239.html