如何打印游标记录?
Posted
技术标签:
【中文标题】如何打印游标记录?【英文标题】:How to print cursor records? 【发布时间】:2020-11-02 04:31:57 【问题描述】:我曾尝试打印游标记录,但不能。下面的代码,我试过了。
DECLARE
CURSOR CUR_EMP IS
SELECT *
FROM EMP
WHERE Deptno = &DNO;
V_REC CUR_EMP%ROWTYPE;
BEGIN
OPEN CUR_EMP;
LOOP
FETCH CUR_EMP INTO V_REC;
EXIT WHEN CUR_EMP%NOTFOUND;
DBMS_OUTPUT.PUT_LINE (
'Record No:'
|| CUR_EMP%ROWCOUNT
|| ' '
|| V_REC.ENAME
|| '
'
|| V_REC.SAL);
END LOOP;
CLOSE CUR_EMP;
END;
【问题讨论】:
【参考方案1】:如果你像以前那样运行它:
SQL> declare
2 cursor cur_emp is select * from emp
3 where deptno = &dno;
4 v_rec cur_emp%rowtype;
5 begin
6 open cur_emp;
7 loop
8 fetch cur_emp into v_rec;
9 exit when cur_emp%notfound;
10
11 dbms_output.put_line('Record no: ' || cur_emp%rowcount ||' '|| v_rec.ename);
12 end loop;
13 close cur_emp;
14 end;
15 /
Enter value for dno: 10
old 3: where deptno = &dno;
new 3: where deptno = 10;
PL/SQL procedure successfully completed. --> there's no output
但是,如果你启用输出...
SQL> set serveroutput on
SQL>
...并再次运行该代码:
SQL> /
Enter value for dno: 10
old 3: where deptno = &dno;
new 3: where deptno = 10;
Record no: 1 CLARK --> oh yes, here they are!
Record no: 2 KING
Record no: 3 MILLER
PL/SQL procedure successfully completed.
SQL>
所以,set serveroutput on
在 SQL*Plus(或 SQL Developer,甚至可能还有更多支持它的工具)中,或者在您的 GUI 中启用它。因为,该代码应该可以正常运行(当然,如果满足WHERE
条件)。
另外,考虑使用更容易维护的游标FOR
循环,因为 Oracle 完成了大部分 dirty 工作(声明游标变量、打开游标、注意退出循环、关闭游标) 为您服务:
SQL> begin
2 for cur_emp in (select rownum rn, e.* from emp e where deptno = &dno) loop
3 dbms_output.put_line('Record no: ' || cur_emp.rn ||' '|| cur_emp.ename);
4 end loop;
5 end;
6 /
Enter value for dno: 10
old 2: for cur_emp in (select rownum rn, e.* from emp e where deptno = &dno) loop
new 2: for cur_emp in (select rownum rn, e.* from emp e where deptno = 10) loop
Record no: 1 CLARK
Record no: 2 KING
Record no: 3 MILLER
PL/SQL procedure successfully completed.
SQL>
【讨论】:
我希望 SO 有一个“喜欢”按钮。当我阅读这个问题时,我正在制定我的答案,只是看到你已经完全按照我的计划做出了回应。 :-) “喜欢”在 SO 上,我猜,叫做“upvote”,@EdStevens :)以上是关于如何打印游标记录?的主要内容,如果未能解决你的问题,请参考以下文章