Oracle游标使用参考语句

一个简单实用:

Declare
	-- 声明游标 
	Cursor Mycur Is
		Select * From Emp;
	Empinfo Emp%Rowtype;
	Cou     Number;
Begin
	-- 游标操作使用循环,但是在操作之前必须先将游标打开 
	For Empinfo In Mycur Loop
		Cou := Mycur%Rowcount;
		Dbms_Output.Put_Line('行号:' || Cou || '   雇员编号:' || Empinfo.Empno || '   雇员姓名:' || Empinfo.Ename);
	End Loop;
End;

 

循环取出数据的两种写法:

Declare
	-- 声明游标 
	Cursor Mycur Is
		Select * From Emp; -- List (EmpPo) 
	Empinfo Emp%Rowtype;
	Cou     Number;
Begin
	-- 游标操作使用循环,但是在操作之前必须先将游标打开 
	If Mycur%Isopen Then
		Null;
	Else
		Open Mycur;
	End If;
	-- 使游标向下一行 
	Fetch Mycur
		Into Empinfo;
	-- 判断此行是否有数据被发现 
	While (Mycur%Found) Loop
		Cou := Mycur%Rowcount;
		Dbms_Output.Put_Line('行号:' || Cou || '    雇员编号:' || Empinfo.Empno || '   雇员姓名:' || Empinfo.Ename);
		-- 修改游标,继续向下 
		Fetch Mycur
			Into Empinfo;
	End Loop;
End;

 

第二种写法:

Declare
	-- 声明游标
	Cursor Mycur Is
		Select * From Emp;
	Empinfo Emp%Rowtype;
	Cou     Number;
Begin
	-- 游标操作使用循环,但是在操作之前必须先将游标打开 
	If Mycur%Isopen Then
		Null;
	Else
		Open Mycur;
	End If;
	Loop
		-- 使游标向下一行 
		Fetch Mycur
			Into Empinfo;
		Exit When Mycur%Notfound;
		Cou := Mycur%Rowcount;
		Dbms_Output.Put_Line('行号:' || Cou || '   雇员编号:' || Empinfo.Empno || '   雇员姓名:' || Empinfo.Ename);
	End Loop;
End;

 在存储过程中使用游标

Create Or Replace Procedure Myproc(Oi_Return Out Integer) Is
	Cursor Mycur Is
		Select * From Emp_0915;
	Empinfo Emp_0915%Rowtype;
	Cou     Number;
	Exc_Return Exception; -- 程序中间返回自定义异常
Begin
	If Mycur%Isopen Then
		Null;
	Else
		Open Mycur;
	End If;
	Loop
		Fetch Mycur
			Into Empinfo;
		Exit When Mycur%Notfound;
		Cou := Mycur%Rowcount;
		Dbms_Output.Put_Line(Cou || '开始更新...');
		Update Emp_0915 t Set t.Sal = t.Sal + 1 Where t.Empno = Empinfo.Empno;
		Dbms_Output.Put_Line(Cou || '更新结束...');
	End Loop;
	Commit;
	Oi_Return := 1;
Exception
	When Exc_Return Then
		Rollback;
		Oi_Return := 0;
End;

 

在oracle中测试:

Declare
	Re Integer;
Begin
	Myproc(Re);
	If Re = 1 Then
		Dbms_Output.Put_Line(Re || ':执行结束。。。');
	Else
		Dbms_Output.Put_Line(Re || ':执行错误_______');
	End If;
End;

 

你可能感兴趣的:(java,oracle,sql,函数,游标)