发表于 2016-11-2 01:50:04

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中存放的值(内存中)已经释放
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
页: [1]
查看完整版本: SQL SERVER T-SQL 游标的初步研究