zoukankan      html  css  js  c++  java
  • SQL游标学习

    游标一般格式:
    DECLARE 游标名称 CURSOR FOR SELECT 字段1,字段2,字段3,... FROM 表名 WHERE ...
    OPEN 游标名称
    FETCH NEXT FROM 游标名称 INTO 变量名1,变量名2,变量名3,...
    WHILE @@FETCH_STATUS=0
            BEGIN
                      SQL语句执行过程... ...
                      FETCH NEXT FROM 游标名称 INTO 变量名1,变量名2,变量名3,...
            END
    CLOSE 游标名称
    DEALLOCATE 游标名称 (删除游标)



    例子:
    /*
    功能:数据库表格tbl_users数据
    deptid userid username
    1          100      a
    1      101      b
    2      102      c
    要求用一个sql语句输出下面结果
    deptid username

    1        ab
    2        c
    [
    要求用游标实现
    设计:
    OK_008
    时间:
    2006-05
    备注:无

    */
    create table #Temp1(deptid int,userid int,username varchar(20)) --待测试的数据表
    create table #Temp2(deptid int,username varchar(20))                --结果表
    --先把一些待测试的数据插入到待测试表#Temp1
    insert into #Temp1
    select 1,100,'a' union all
    select 1,101,'b' union all
    select 1,131,'d' union all
    select 1,201,'f' union all
    select 2,302,'c' union all
    select 2,202,'a' union all
    select 2,221,'e' union all
    select 3,102,'y' union all
    select 3,302,'e' union all
    select 3,121,'t'
    --
    declare @deptid int,@username varchar(20)
    --定义游标
    declare Select_cursor cursor for
            select deptid,username from #Temp1
    open Select_cursor
    fetch next from Select_cursor into @deptid,@username    --提取操作的列数据放到局部变量中
    while @@fetch_status=0      --返回被 FETCH 语句执行的最后游标的状态
    /*
    @@FETCH_STATUS =0          FETCH 语句成功
    @@FETCH_STATUS =-1 FETCH 语句失败或此行不在结果集中
    @@FETCH_STATUS =-2 被提取的行不存在
    */
            begin
                      --当表#Temp2deptid存在相同的数据时,就直接在列username上追加@username
                      if(exists(select * from #Temp2 where deptid=@deptid ))
                              update #Temp2 set username=username +@username where deptid=@deptid
                      else
                      --插入新数据
                              insert into #Temp2 select @deptid,@username
                      fetch next from Select_cursor into @deptid,@username
            end
    close Select_cursor     
    deallocate Select_cursor
    select * from #Temp2 --测试结果
    Drop table #Temp1,#Temp2

  • 相关阅读:
    Unity Shader入门精要之 screen post-processing effect
    Unity---关于游戏小包的记录
    计算机基础补充之原码、反码、补码
    C#接口实现技巧之借助第三方
    lua中产生 1
    游戏文本本地化(一)
    xlua修复C#的委托事件的时候,需要提前做好配置
    xlua 实现协程替换Unity中的协程
    C#定义只能处理枚举类型的泛型类型
    C# : 泛型的继承关系实现的一个可以存放不同数据类型的链表
  • 原文地址:https://www.cnblogs.com/aoyihuashao/p/1623725.html
Copyright © 2011-2022 走看看