Oracle 10g数据库游标的使用学习二

游标格式:
CURSOR cursor_name[(parameter[,parameter]...)][return return_type]IS select_statement;


游标的声明
/*
无参数的游标声明
*/
cursor c1 is select t.business_id , t.business_type from tbl_flow_work t;

/*
有参数的游标声明
*/
cursor c2 return tbl_flow_work%rowtype is select t.business_id , t.business_type from t bl_flow_work t where 	t.flow_work_id =1;
cursor cursor_a(temp_bussid number) is select tba.business_name as bn from tbl_business_a tba where tba.business_id = temp_bussid;


游标的使用:
/*
游标只有在打开才能执行查询操作,OPEN语句会把满足查询条件的行锁住,
执行OPEN语句不会选取出结果集中的记录,只有在使用FETCH语句的时候才能将数据读取出来
*/
open c(parameter);
	loop fetch c into v_businessname;
    exit when c%notfound;
		dbms_output.put_line(v_businessname);
	end loop;
close c;


/*
在大多数需要使用显示游标的情况下,都可以用一个游标FOR循环来代替OPEN、FETCH和CLOSE语句,这样可以省去一些繁琐的代码。
游标FOR隐式地声明了一个%ROWTYPE类型的记录作为它的 循环索引,打开游标,
然后反复地执行把结果集中的行放到索引中去,最后在所有行都被处理完成后关闭游标。
*/
[/b]
for cfw in cursor_flowwork loop
  v_busstype := cfw.bt;
  dbms_output.put_line(v_busstype);
end loop;


实践

手动打开游标
-- Created on 2012/12/11 by ZHENGTIAN 
declare 
  -- 定义游标变量
  flow_name_like varchar2(256):= 'zt';
  flow_name varchar2(256);
  flow_code varchar2(256);
  cursor flow_cursor(flow_name_prefix varchar2) is select f.flow_name,f.flow_code from pdc_flow f where f.flow_name like '%'||flow_name_prefix||'%';
begin
  open flow_cursor(flow_name_like);
  	loop fetch flow_cursor into flow_name,flow_code;
      exit when flow_cursor%notfound;
  		dbms_output.put_line('flow_name:'||flow_name||';flow_code:'||flow_code);
  	end loop;
  close flow_cursor;
end;


用for循环使用游标,省略手动打开游标语句
-- Created on 2012/12/11 by ZHENGTIAN 
declare 
  -- 定义游标变量
  flow_name_like varchar2(256):= 'zt';
  flow_name varchar2(256);
  flow_code varchar2(256);
  cursor flow_cursor(flow_name_prefix varchar2) is select f.flow_name,f.flow_code from pdc_flow f where f.flow_name like '%'||flow_name_prefix||'%';
begin
  /*open flow_cursor(flow_name_like);
  	loop fetch flow_cursor into flow_name,flow_code;
      exit when flow_cursor%notfound;
  		dbms_output.put_line('flow_name:'||flow_name||';flow_code:'||flow_code);
  	end loop;
  close flow_cursor;*/
  for flow in flow_cursor(flow_name_like) loop
    flow_name := flow.flow_name;
    flow_code :=flow.flow_code;
    dbms_output.put_line('flow_name:'||flow_name||';flow_code:'||flow_code);
  end loop;
end;

猜你喜欢

转载自zheng12tian.iteye.com/blog/1746054