zoukankan      html  css  js  c++  java
  • 使用游标的存储过程

    USE [JSKEEP]--库名
    GO
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    ALTER PROCEDURE [dbo].[Proc_Enterprise_Info]
    AS
    --===============================================================================
    
      BEGIN
        DECLARE
          @id      VARCHAR(40),  ---信息id
          @unique_code  BIGINT,  --唯一编码
          @unique_codes BIGINT   --当前信息中的unique_code
        
        --给变量@unique_code赋值设置为最大唯一编码
        select @unique_code =  max(unique_code) from t_unified_enterprise_info;
        -- 定义游标.
        DECLARE mycursor CURSOR  FOR
        --根据psname和unique_code去重结果集
        select min(id) as id from t_unified_enterprise_info 
            where psname is not null and psname = ltrim(rtrim(psname)) group by psname,region_code having count(region_code)=1
        --打开游标
        OPEN mycursor
        --填充数据
        FETCH NEXT FROM mycursor INTO @id
        --判断游标的状态  
        -- 0 fetch语句成功      
        ---1 fetch语句失败或此行不在结果集中      
        ---2 被提取的行不存在  
        WHILE @@FETCH_STATUS = 0
          BEGIN
            --给变量@unique_code赋值设置为最大唯一编码(放在这里处理每条数据的时候都要进行一次查询,严重拖慢执行速度,所以提到上面去)
            --select @unique_code =  max(unique_code) from t_unified_enterprise_info;
            select @unique_codes = unique_code from t_unified_enterprise_info where id = @id;
            
            if (@unique_code is NULL )
                BEGIN
                    set @unique_code = 110000000000;
                END
            else
                BEGIN
                        set @unique_code = @unique_code + 1;
                END
            --如果该条记录已经有唯一编码,则保持唯一编码不变
            if (@unique_codes>0)
                BEGIN
                    set @unique_code = @unique_codes;
                END 
            
            update t_unified_enterprise_info set unique_code = @unique_code,main_or_child = 1 where id = @id;
            --用游标去取下一行记录
            FETCH NEXT FROM mycursor INTO @id
          END
        --关闭游标
        CLOSE mycursor
        --删除游标
        DEALLOCATE mycursor
      END    

    上面代码是使用游标的参考例子

  • 相关阅读:
    spring
    Hibernate中一级缓存和二级缓存使用详解
    myeclipse 配置weblogic
    小程序animation动画效果综合应用案例(交流QQ群:604788754)
    PHP:第二章——PHP中的equire与incude语句
    PHP:第二章——PHP中的break一continue一return语句
    PHP:第二章——PHP中的for语句
    PHP:第二章——PHP中的while语句
    PHP:第二章——PHP中的流程控制语句
    小程序animation动画效果(小程序组件案例)
  • 原文地址:https://www.cnblogs.com/shuilangyizu/p/5944587.html
Copyright © 2011-2022 走看看