oracle中通过游标实现查询
1.通过提取数据
declare
v_result sys_refcursor;
v_id int;
v_name varchar2(20);
begin
open v_result for select empno,ename from emp;
loop
fetch v_result into v_id,v_name;
exit when v_result%notfound;
dbms_output.put_line('列id的值:'||to_char(v_id));
dbms_output.put_line('列name的值:'||v_name);
end loop;
close v_result;
exception
when others then
dbms_output.put_line(sqlerrm);
end;
2.通过for循环
DECLARE
CURSOR emp_cursor IS
SELECT empno, ename FROM emp;
BEGIN
FOR Emp_record IN emp_cursor LOOP
DBMS_OUTPUT.PUT_LINE(Emp_record.empno|| Emp_record.ename);
END LOOP;
END;
3.另一种形式的for循环
BEGIN
FOR re IN (SELECT ename FROM EMP) LOOP
DBMS_OUTPUT.PUT_LINE(re.ename)
END LOOP;
END;
4.游标的属性
- %ROWCOUNT 整型 获得FETCH语句返回的数据行数
- %FOUND 布尔型 最近的FETCH语句返回一行数据则为真,否则为假
- %NOTFOUND 布尔型 与%FOUND属性返回值相反
- %ISOPEN 布尔型 游标已经打开时值为真,否则为假
declare
names varchar2(20);
cursor emp_cursor is
select ename from emp;
begin
open emp_cursor;
if emp_cursor%isopen then
loop
fetch emp_cursor into names;
exit when emp_cursor%notfound;
DBMS_OUTPUT.PUT_LINE(emp_cursor%ROWCOUNT||names);
end loop;
else
DBMS_OUTPUT.PUT_LINE('没有相关信息');
end if;
close emp_cursor;
end;
5.带参数的游标
DECLARE
V_empno NUMBER(5);
V_ename VARCHAR2(10);
CURSOR emp_cursor(p_deptno NUMBER, p_job VARCHAR2) IS
SELECT empno, ename FROM emp
WHERE deptno = p_deptno AND job = p_job;
BEGIN
OPEN emp_cursor(10, 'CLERK');
LOOP
FETCH emp_cursor INTO v_empno,v_ename;
EXIT WHEN emp_cursor%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(v_empno||','||v_ename);
END LOOP;
END;