zoukankan      html  css  js  c++  java
  • SQL数据库使用游标示例 Yang

    记录一下!

    --学生成绩表 
    CREATE TABLE tb 
    ( 
      username NVARCHAR(10), 
      course NVARCHAR(10), 
      mark INT 
    ) 
    --填充数据 
    INSERT INTO dbo.tb (username, course, mark) 
    VALUES ('张三', '语文', 74) 
    GO 
    INSERT INTO dbo.tb (username, course, mark) 
    VALUES ('张三', '数学', 83) 
    GO 
    INSERT INTO dbo.tb (username, course, mark) 
    VALUES ('张三', '英语', 93) 
    GO 
    INSERT INTO dbo.tb (username, course, mark) 
    VALUES ('李四', '语文', 74) 
    GO 
    INSERT INTO dbo.tb (username, course, mark) 
    VALUES ('李四', '数学', 84) 
    GO 
    INSERT INTO dbo.tb (username, course, mark) 
    VALUES ('李四', '英语', 94) 
    GO
    
    --新建一个临时表 
    CREATE TABLE #temp ( 
      stuName NVARCHAR(20), 
      stuMarks INT     
    ) 
    DECLARE 
        @stuName NVARCHAR(20), 
        @stuMark INT 
    --定义一个游标 
    DECLARE myCursor CURSOR 
    FOR 
      --向游标中添加内容 
      SELECT userName,sum(MARK) FROM tb t GROUP BY t.username 
    --打开游标 
    OPEN myCursor 
    --进行操作 
    FETCH NEXT FROM myCursor INTO @stuName,@stuMark 
    --@@FETCH_STATUS=0:表示上面那条操作成功,-1表示不存在或不在结果集当中,-2提取行不存在 
    --WHILE 循环读取游标内容 
    WHILE @@FETCH_STATUS=0 
      BEGIN 
        INSERT INTO #temp(stuName,stuMarks) VALUES (@stuName,@stuMark); 
        FETCH NEXT FROM myCursor INTO @stuName,@stuMark 
      END 
    --关闭游标 
    CLOSE myCursor 
    --删除游标变量或游标同游标之间的引用关系 
    DEALLOCATE myCursor
    
    SELECT * FROM #temp
  • 相关阅读:
    Android框架: MVC MVP MVVM
    Apache Tomcat -8.0.45
    【MySQL】Database connections will be migrated
    MySQL(mysql-installer-community-5.7.18.1 Windows10)
    代码版本控制(Source Control)
    HTML 5
    微信小程序
    Android Studio 2.3.3 安装
    React Native
    2018面向对象程序设计(Java)第12周学习指导及要求
  • 原文地址:https://www.cnblogs.com/Yang2012/p/2935135.html
Copyright © 2011-2022 走看看