SQL游标用法(二)

游标:是用来对表从上下每行循环取值,将值连接成为字符串.
例子:
对 pubs 数据库的dbo.titles 表。
  1.取得表中的总价格:select sum(price) from dbo.titles
  2.但是我想得到这样一个结果:书名,价格。
精通ASP,39元;学习vc++,28元;JAVA编程,23元
则用到游标:

声明游标:
 declare titprice CURSOR FAST_FORWARD for
select title, price from dbo.titles where price<15

打开游标:
open titprice

循环取质
fetch next from titprice into @strtitle,@strprice
while @@fetch_status=0
 begin
   if @str=''
   set @str=@strtitle+':   '+Convert(varchar(20),@strprice) 
  else
    set @str=@str+@strtitle+':   '+Convert(varchar(20),@strprice)  

  fetch next from titprice into @strtitle,@strprice
end

关闭游标
close titprice
释放游标
DEALLOCATE titprice


print @str

原文地址:https://www.cnblogs.com/ly5201314/p/1369712.html