我不确定你为什么如此关注匿名区块;尽管可以这样做,但您的任务说要使用存储过程(我认为它也可以是一个函数);此外,程序更有意义。
无论如何,这是一个 SQL*Plus 示例,它显示了如何做到这一点:
SQL> set pagesize 100
SQL> set verify off
SQL>
SQL> var choice number;
SQL> var rc refcursor;
SQL>
SQL> begin
2 if &&choice = 1 then
3 open :rc for select * from dept;
4 elsif &&choice = 2 then
5 open :rc for select * From bonus;
6 elsif &&choice = 3 then
7 open :rc for select d.dname, e.ename, e.job
8 from dept d join emp e on e.deptno = d.deptno;
9 end if;
10 end;
11 /
Enter value for choice: 2
PL/SQL procedure successfully completed.
SQL> print :rc
ENAME JOB SAL COMM
---------- --------- ---------- ----------
KING PRESIDENT 1000 100
SQL> undefine choice
SQL> /
Enter value for choice: 3
PL/SQL procedure successfully completed.
SQL> print :rc
DNAME ENAME JOB
-------------------- ---------- ---------
ACCOUNTING CLARK MANAGER
ACCOUNTING KING PRESIDENT
ACCOUNTING MILLER CLERK
RESEARCH JONES MANAGER
RESEARCH FORD ANALYST
RESEARCH ADAMS CLERK
RESEARCH SMITH CLERK
RESEARCH SCOTT ANALYST
SALES WARD SALESMAN
SALES TURNER SALESMAN
SALES ALLEN SALESMAN
SALES JAMES CLERK
SALES BLAKE MANAGER
SALES MARTIN SALESMAN
14 rows selected.
SQL>
使用函数的选项如下所示;如您所见,它与前面的示例几乎相同。
SQL> create or replace function f_test (par_choice in number)
2 return sys_refcursor
3 is
4 rc sys_refcursor;
5 begin
6 if par_choice = 1 then
7 open rc for select * from dept;
8 elsif par_choice = 2 then
9 open rc for select * From bonus;
10 elsif par_choice = 3 then
11 open rc for select d.dname, e.ename, e.job
12 from dept d join emp e on e.deptno = d.deptno;
13 end if;
14
15 return rc;
16 end;
17 /
Function created.
SQL> select f_test(2) from dual;
F_TEST(2)
--------------------
CURSOR STATEMENT : 1
CURSOR STATEMENT : 1
ENAME JOB SAL COMM
---------- --------- ---------- ----------
KING PRESIDENT 1000 100
SQL> select f_test(1) from dual;
F_TEST(1)
--------------------
CURSOR STATEMENT : 1
CURSOR STATEMENT : 1
DEPTNO DNAME LOC
---------- -------------------- --------------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
SQL>