Sql cursor 基本应用

来源:互联网 发布:mac怎么卸载java 编辑:程序博客网 时间:2024/05/16 01:00

1、游标格式:

DECLARE 游标名称 CURSOR FOR SELECT 字段1,字段2,字段3,... FROM 表名 WHERE ...
OPEN 游标名称
FETCH NEXT FROM 游标名称 INTO 变量名1,变量名2,变量名3,...
WHILE @@FETCH_STATUS=0
    BEGIN
       SQL语句执行过程... ...
       FETCH NEXT FROM 游标名称 INTO 变量名1,变量名2,变量名3,...
    END
CLOSE 游标名称
DEALLOCATE 游标名称 (删除游标)

2、游标应用实例:

table1结构如下:id    intname  varchar(50)declare @id intdeclare @name varchar(50)declare cursor1 cursor for --定义游标cursor1select id,name from table1 --使用游标的对象【必须是表结构,如果按符号分割的字符串可以用fn_split分割成临时表的结构】open cursor1               --打开游标fetch next from cursor1 into @id,@name  --将游标向下移1行,获取的数据放入之前定义的变量@id,@name中while @@fetch_status=0           --判断是否成功获取数据begin    update table1 set name=name+'1'    where id=@id                           --进行相应处理(跟据需要填入SQL文)    fetch next from cursor1 into @id,@name  --将游标向下移1行【如果执行完多一行,那就是Fetch的格式没写对】endclose cursor1                   --关闭游标deallocate cursor1              <span style="font-family: Arial;">--删除游标</span>
3、游标可以嵌套:嵌套时必须按照实例2中的fetch的格式写游标,否则会导致内部游标错乱

declare id_cursor cursor forselect street_id from mapping_street_mergeopen id_cursordeclare @street_id intset @street_id = 0fetch next from id_cursor into @street_idwhile @@FETCH_STATUS=0beginfetch next from street_cursor into @index_idwhile @@FETCH_STATUS=0begin--Do somethingfetch next from street_cursor into @index_idendclose street_cursordeallocate street_cursor--Do somethingfetch next from id_cursor into @street_idendclose id_cursordeallocate id_cursor


1 0