sql 游标

游标的作用:

主要是用查询出来的数据集做循环的时候用到!


--  create table test
-- (
--  id int identity(1,1) primary key,
--  name varchar(50)
-- )

declare @id int
declare @name varchar(50)
declare cursor1 cursor for         --定义游标cursor1
select * from test          --使用游标的对象(跟据需要填入select文)
open cursor1                       --打开游标

fetch next from cursor1 into @id,@name  --将游标向下移1行,获取的数据放入之前定义的变量@id,@name中

while @@fetch_status=0           --判断是否成功获取数据
begin
update test set name=name+'1'
where id=@id                           --进行相应处理(跟据需要填入SQL文)

fetch next from cursor1 into @id,@name  --将游标向下移1行
end

close cursor1                   --关闭游标
deallocate cursor1

select * from test
--
-- insert test(name) values('aaa')
--
-- insert test(name) values('aaa')
--
-- insert test(name) values('aaa')
--
-- insert test(name) values('aaa')

--update test set name='aaa'

===================================================结果

(所影响的行数为 1 行)

(所影响的行数为 1 行)

(所影响的行数为 1 行)

(所影响的行数为 1 行)

id          name                                              
----------- --------------------------------------------------
1           aaa1
2           aaa1
3           aaa1
4           aaa1

(所影响的行数为 4 行)

posted @ 2009-08-30 23:57  zxlin25  阅读(253)  评论(1编辑  收藏  举报