34,590
社区成员
发帖
与我相关
我的任务
分享
--测试数据准备
if(object_id('t1') is not null)drop table t1
CREATE table t1(
id int identity(1,1) primary key,
value nvarchar(20)
)
go
--插入测试数据
insert into t1(value)
select '值1'union all
select '值2'union all
select '值3'union all
select '值4'
--查看结果集合
--select * from t1
if(OBJECT_ID('p_print')is not null) drop procedure p_print
go
create procedure p_print
as
begin
declare @value nvarchar(20)--注意这里的变量类型应该与游标中读取出来的字段类型相同
--创建游标
declare cur1 cursor for
select value from t1
--打开游标
open cur1
fetch next from cur1 into @value--这里的@value对应游标每条记录中的字段value的值
while(@@FETCH_STATUS = 0)
begin
print 'value:'+@value
fetch next from cur1 into @value
end
--关闭游标
close cur1
--释放游标
DEALLOCATE cur1
end
--调用(去注释调用)
--exec p_print
/* 执行结果
value:值1
value:值2
value:值3
value:值4
*/