SQL SERVER T-SQL 游标的初步研究

 

 

好久没有来iteye了,准备离开it行业,算了还是回来

 

最近在看SQL SERVER 游标这节的内容 感觉很有意思,写下来,方便以后我自己看

 

游标简单点就是对数据集合的处理,但是我们有时候只需要处理其中的一行,游标很有用

当然其实也可以用控制流语句来实现

 

 

题目  用循环输出表中的某列

一方式: 

use TEST;--测试数据库

 declare @n int = (select MIN(tb.id) from test_tb tb)

 declare @num int = (select max(tb.ID) from test_tb tb)

 while(@n<=@num)

 begin

  select  tb.id as '主键号', tb.name  as '列中内容' from test_tb tb  where tb.id=@n

  set @n = @n+1      

 end 

 

二方式: 

declare @youbiaoNeiRong varchar(2000) 

declare cur_test1 cursor for

select tb.name  from test_tb tb

open cur_test1 

fetch  cur_test1  into @youbiaoNR --- a

while @@FETCH_STATUS=0  --  b

begin  

select @youbiaoNR as 姓名

fetch  cur_test1  into @youbiaoNR

end

close cur_test1

--   c  print @youbiaoNR

deallocate cur_test1

-- d   if  @youbiaoNR<>''

-- (d)   print 0

 

注  a    fetch  表示把 selec 的内容放入  @youbiaoNeiRong

      b   @@FETCH_STATUS=0  是指结果集中的某一行 , 循环中注意  每fetch  一次 行数就+1

        c    close  是指游标关闭,但是@youbiaoNeiRong中存放的值(内存中)还没有释放

        d   deallocate   是指游标关闭,但是@youbiaoNeiRong中存放的值(内存中)已经释放

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值