zoukankan      html  css  js  c++  java
  • SQL Server 初识游标

    ---恢复内容开始---

       

      游标:游标是一种能从包含多个数据的结果集每次提取一条的机制

        游标的特点是: 

        •  检索得到的数据集更加灵活
        •  可有针对性的对数据进行操作
        •  拥有对数据进行删除和更新的能力 

        为何使用游标: 

        • 游标提供了一种比较好的解决方案,可以将批操作变成行操作。 

        游标的步骤

      1.    定义游标
      2.    打开游标
      3.    使用游标
      4.    关闭游标
      5.    删除游标

        代码详解:

          1. 定义游标

            DECLARE  游标名  [ INSENSITIVE ] [ SCROLL ] CURSOR 
              FOR T-SQL 语句

          2. 打开游标

             OPEN 游标名

          

          3.  使用游标

            FETCH
                   [ NEXT | PRIOR | FIRST | LAST
                        | ABSOLUTE { n | @nvar }
                        | RELATIVE { n | @nvar }
                    ] 
                  FROM  游标名 
             into 给局部变量赋值

              
     
              ps 只有在定义游标时设置为SCROLL , 才可使用除 NEXT 其他标签 

          4. 关闭游标

            CLOSE 游标名

          5. 删除游标

                 DEALLOCATE 游标名        

          

    示例:

      前提:     表 stuscore 

           表内数据:

              

      目的:   将表改成如图形式

          

        代码     

            /*定义局部变量,用于存储sql语句*/
          declare @sql varchar(max)       set @sql='select distinct( sname )'         /*定义游标使用的的局部变量*/       declare @cname varchar(20)         /*定义游标*/       declare cur_stuscore cursor read_only for select distinct(cname) from stuscore         /*打开游标*/       open cur_stuscore         /*使用游标*/       fetch next from cur_stuscore into @cname         /*使用while循环,使语句遍历整表*/       while(@@FETCH_STATUS=0)         begin          set @sql=@sql+',(select s.score from stuscore s where s.cname='''+@cname+''' and s.sname=t.sname)as '''+@cname+''''          fetch next from cur_stuscore into @cname         end         /*更新SQL语句*/       set @sql=@sql+' from stuscore t'         /*执行SQL语句*/       exec (@sql)         /*关闭游标*/       close cur_stuscore         /*删除游标*/       deallocate cur_stuscore


    ps: SQL执行语句为:
     

         select distinct( sname ),
         (select s.score from stuscore s where s.cname='语文' and s.sname = t.sname) as '语文',

          (select s.score from stuscore s where s.cname='数学' and s.sname = t.sname) as '数学',

           (select s.score from stuscore s where s.cname='英语' and s.sname = t.sname) as '英语' 

         from stuscore t
  • 相关阅读:
    如何在Windows Forms应用程序中实现可组装式(Composite)的架构以及松耦合事件机制
    SQL Server 2008中的CDC(Change Data Capture)功能使用及释疑
    【VSTO】Office开发中遇到的兼容性检查问题
    SQL Server 2008 R2的StreamInsight 【文章转载】
    WCF技术的不同应用场景及其实现分析
    如何利用Interception简化MVVM中的Model和ViewModel的设计
    有关在SharePoint Server中Infopath表单无法呈现的问题及解决方案
    再谈谈ADO.NET Data Service 数据格式(xml和json)
    自定义Domain Service时遇到实体不能更新的问题及其解决方案
    如何在RIA Service中启用身份验证
  • 原文地址:https://www.cnblogs.com/ang-664455/p/7096717.html
Copyright © 2011-2022 走看看