這裏是一個強類型的引用遊標的過程:
SQL> create or replace procedure p1 is
2 type dept_rc is ref cursor return dept%rowtype;
3 my_ref_cursor dept_rc;
4 begin
5 open my_ref_cursor for
6 select * from dept;
7 end;
8/
Procedure created.
SQL>
因爲EMP記錄的簽名不匹配DEPT表的下面一條語句失敗。
SQL> create or replace procedure p1 is
2 type dept_rc is ref cursor return dept%rowtype;
3 my_ref_cursor dept_rc;
4 begin
5 open my_ref_cursor for
6 select * from emp;
7 end;
8/
Warning: Procedure created with compilation errors.
SQL> show error
Errors for PROCEDURE P1:
LINE/COL ERROR
-------- -----------------------------------------------------------------
5/5 PL/SQL: SQL Statement ignored
6/9 PLS-00382: expression is of wrong type
SQL>
但如果我們改變投影匹配DEPT表,然後我們再有成功:
SQL> create or replace procedure p1 is
2 type dept_rc is ref cursor return dept%rowtype;
3 my_ref_cursor dept_rc;
4 begin
5 open my_ref_cursor for
6 select deptno, ename, job from emp;
7 end;
8/
Procedure created.
SQL>
所以,爲什麼我們不能用一個強類型的REF光標使用動態SQL?
SQL> create or replace procedure p1 is
2 type dept_rc is ref cursor return dept%rowtype;
3 my_ref_cursor dept_rc;
4 begin
5 open my_ref_cursor for
6 'select * from dept';
7 end;
8/
Warning: Procedure created with compilation errors.
SQL> show error
Errors for PROCEDURE P1:
LINE/COL ERROR
-------- -----------------------------------------------------------------
5/5 PL/SQL: Statement ignored
5/10 PLS-00455: cursor 'MY_REF_CURSOR' cannot be used in dynamic SQL
OPEN statement
SQL>
因爲編譯器無法解析動態SQL語句中的字符串。所以它不能斷言查詢投影中的列與數字匹配並且數據類型是引用遊標的簽名。因此它無法驗證引用遊標變量和查詢之間的契約。當我們認爲動態SQL語句可以從USER_TAB_COLUMNS上的一個查詢中組合出來時,爲什麼不能這麼做呢?
來源
2010-05-06 19:21:20
APC