动态sql使用,dbms_sql的使用

create or replace procedure pro_dict_proteam is  
/**  
  利用dbms_sql执行select语句,其顺序为  
  open cursor-->parse-->define column-->execute  
  -->fetch rows-->close cursor;  
**/  
       --定义变量  
       v_cursor number;--游标ID  
       v_sql varchar2(500);--用于存放sql语句  
        v_proteam_id number;--班组ID  
        v_proteam_name varchar2(50);--班组名称  
        v_count number;--在这里没有实际的含义,只是存放函数返回值  
        --v_jctype varchar(20):=',SS3B,';  
        v_workflag number:=1;--查询条件字段  
 begin  
        --:v_workflag是占位符  
        --select语句中的第一列是proteamid,第二列是proteamname  
        v_sql:='select proteamid,proteamname from dict_proteam where workflag=:v_workflag';  
        v_cursor:=dbms_sql.open_cursor;--打开游标  
        dbms_sql.parse(v_cursor,v_sql,dbms_sql.native);--解析动态sql语句  
        --绑定输入参数,v_workflag的值传给:v_workflag  
        dbms_sql.bind_variable(v_cursor,':v_workflag',v_workflag);  
        --定义列,v_proteam_id对应select语句中的第一列  
        dbms_sql.define_column(v_cursor,1,v_proteam_id);  
        --定义列,v_proteam_name对应select语句中的第二列,长度为50  
        dbms_sql.define_column(v_cursor,2,v_proteam_name,50);  
        --执行动态sql语句  
        v_count:=dbms_sql.execute(v_cursor);  
        dbms_output.put_line('v_count='||v_count);  
        loop  
               --fetch_rows在结果集中移动游标,如果未抵达末尾,返回1  
               --从游标中把数据检索到缓存区(buffer)中,缓冲区的值只能被函数  
               --column_value()所读取  
               exit when dbms_sql.fetch_rows(v_cursor)<=0;  
               --把缓冲区的列的值读入到相应变量中  
               --将当前行的查询结果写入上面定义的列中  
               --第一列的值被读入v_proteam_id中  
               dbms_sql.column_value(v_cursor,1,v_proteam_id);  
               --第二列的值被读入v_proteam_name中  
               dbms_sql.column_value(v_cursor,2,v_proteam_name);  
               --打印变量的值  
               dbms_output.put_line(v_proteam_id||' '||v_proteam_name);  
        end loop;  
        dbms_sql.close_cursor(v_cursor);--关闭游标  
 end;  

猜你喜欢

转载自blog.csdn.net/lzl1101206656/article/details/80509958