如何解决此pl sql oracle查询?

时间:2018-12-01 08:44:32

标签: plsql

  1. 使用While循环编写PL / SQL程序以显示所有DEPTNO,DNAME和LOC 从DEPT表中。假设两个deptno之差为10。

我是初学者,很困惑解决此查询,请帮助解决此问题。

2 个答案:

答案 0 :(得分:0)

这是您所要求的方法,但是请记住,这不是最佳的方法。如果您的目标是在PLSQL中的While循环上训练自己,那么就可以了。

DECLARE
   CURSOR C_DEPTS
   IS
      SELECT DEPTNO, DNAME, LOC FROM DEPT;

   V_DEPTNO   VARCHAR2 (255);
   V_DNAME    VARCHAR2 (255);
   V_LOC      VARCHAR2 (255);
BEGIN
   OPEN C_DEPTS;

   FETCH C_DEPTS INTO V_DEPTNO, V_DNAME, V_LOC;

   WHILE C_DEPTS%FOUND
   LOOP
      DBMS_OUTPUT.PUT_LINE ('DEPTNO = ' || V_DEPTNO);
      DBMS_OUTPUT.PUT_LINE ('DNAME = ' || V_DNAME);
      DBMS_OUTPUT.PUT_LINE ('LOC = ' || V_LOC);

      FETCH C_DEPTS INTO V_DEPTNO, V_DNAME, V_LOC;
   END LOOP;
END;

答案 1 :(得分:0)

像这样吗?

SQL> set serveroutput on
SQL> declare
  2    i            dept.deptno%type;   -- loop counter
  3    l_max_deptno dept.deptno%type;   -- upper limit
  4    l_dept_row   dept%rowtype;       -- will contain the whole DEPT table row
  5  begin
  6    -- MIN -> i (which will be the starting point); MAX -> l_max_deptno (which will be the end)
  7    select min(deptno), max(deptno)
  8      into i, l_max_deptno
  9      from dept;
 10
 11    while i <= l_max_deptno
 12    loop
 13      -- select the whole row into L_DEPT_ROW
 14      select *
 15        into l_dept_row
 16        from dept
 17        where deptno = i;
 18
 19      dbms_output.put_line(l_dept_row.deptno ||' - '||
 20                           l_dept_row.dname  ||' - '||
 21                           l_dept_row.loc);
 22      -- increment counter by 10 (because, as you said, the difference is 10)
 23      i := i + 10;
 24    end loop;
 25  end;
 26  /
10 - ACCOUNTING - NEW YORK
20 - RESEARCH - DALLAS
30 - SALES - CHICAGO
40 - OPERATIONS - BOSTON

PL/SQL procedure successfully completed.

SQL>