zoukankan      html  css  js  c++  java
  • 游标

    游标:即从某一结果集中逐一地读取一条记录。缺点:所占资源大。

    游标四部分:1.DECLARE游标 2.open游标 3.从一个游标中FETCH信息4.CLOSE或DEALLOCATE游标

    声明游标:

    declare cur_authors cursor

    for

    select id,name,phone,address from authors

    for update(for read only)(for update of au_lname,au_fname    /*只允许修改这两列*/)

    FETCH命令语法规则为:

    FETCH

    [[NEXT|PRIOR|FIRST|LAST|ABSOLUTE{n|@nvar}|RELATIVE{n|@nvar}]FROM]cursor_name

    [INTO @variable_name1,@variable_name2...]

    进行定位修改或删除游标中数据的语法规则为:

    UPDATE table_name

    set column_name=expression

    where current of cursor_name

    DELETE from table_name

    where current of cursor_name

    游标例子1:

    declare @au_id varchar(11),@au_lname varchar(40),@au_fname varchar(20)

    declare authors_cur cursor

    for

    select au_id,au_lname,au_fname from authors

    for update of au_id,au_lname,au_fname  

    open authors_cur 

    fetch next from authors_cur into @au_id,@au_lname,@au_fname

    while @@fetch_status=0

    Begin

    if @au_id='1772-32-1176'

    update authors

    set au_lname='smith',au_fname='jake'

    where current of authors_cur

    fetch next from authors_cur into @au_id,@au_lname,@au_fname

    end

    deallocate authors_cur/*释放游标*/(close the cursor)

     游标例子2:

    declare @Id int,@DepartmentId int
    -- 1.declare cursor
    DECLARE risk_cur CURSOR FOR
    select Id,DepartmentId from ProtectionRisk

    -- 2.open cursor
    OPEN risk_cur
    -- 3.fetch data from cursor then use it
    FETCH risk_cur INTO @Id,@DepartmentId  --select fields in the step 1
    WHILE @@FETCH_STATUS=0
    BEGIN
    update Entity_To_ProtectionRisk set DepartmentId=(select DepartmentId from ProtectionRisk where id=@Id) where ProtectionRiskId=@Id

    FETCH NEXT FROM risk_cur INTO @ID,@DepartmentId 
    END;

    -- 4.close cursor
    CLOSE risk_cur;

    -- 5.release cursor
    DEALLOCATE risk_cur;

  • 相关阅读:
    python-进阶-优雅的python写法
    springMVC3学习(十一)--文件上传CommonsMultipartFile
    springMVC3学习(十)--注解式控制器
    CSS3/jQuery自定义弹出窗口
    window.open()详解及浏览器兼容性问题
    空格&nbsp在不同浏览器中显示距离不一致问题解决方法
    jQuery拖动调整表格列宽度-resizableColumns
    jQuery表格排序组件-tablesorter
    springMVC3学习(九)--redirect和forward跳转
    springMVC3学习(八)--全局的异常处理
  • 原文地址:https://www.cnblogs.com/cw_volcano/p/1947527.html
Copyright © 2011-2022 走看看