Oracle DBMS_SQL 给出的 ORA-1007 变量不在选择列表中

问题描述 投票:0回答:1

我在 Oracle 11g 和 19c 上得到了这个。

下面是我用来动态处理一些查询的代码的简化示例。它需要是 DBMS_SQL,因为实际用例将生成各种具有不同列名称和类型的查询。

代码:

SET SERVEROUTPUT ON
DECLARE
  l_qry VARCHAR2(1000) := 'SELECT TO_CHAR(SYSDATE) td FROM DUAL';
  l_cursor_id  INTEGER;
  l_col_val    VARCHAR2(4000);
  l_status     INTEGER;
  l_num_cols   NUMBER := 0;
  l_cols_desc  DBMS_SQL.DESC_TAB;
BEGIN
  l_cursor_id := DBMS_SQL.OPEN_CURSOR;
  DBMS_SQL.PARSE( l_cursor_id, l_qry, DBMS_SQL.NATIVE );
  DBMS_SQL.DESCRIBE_COLUMNS( l_cursor_id, l_num_cols, l_cols_desc );
  l_status := DBMS_SQL.EXECUTE ( l_cursor_id );
  FOR idx IN 1 .. l_num_cols LOOP
    DBMS_OUTPUT.PUT_LINE( 'Col num ' || idx || ' is "' || l_cols_desc(idx).col_name || '"' );
  END LOOP;
  LOOP
    l_status := DBMS_SQL.FETCH_ROWS( l_cursor_id );
    EXIT WHEN l_status <= 0;
    FOR idx IN 1 .. l_num_cols  LOOP
      DBMS_OUTPUT.PUT_LINE( ' Get col val ' || idx );
      DBMS_SQL.COLUMN_VALUE( l_cursor_id, idx, l_col_val );
      DBMS_OUTPUT.PUT_LINE( ' Value: ' || l_col_val );
    END LOOP;
  END LOOP;
  DBMS_SQL.CLOSE_CURSOR( l_cursor_id );
END;
/

我运行的结果是:

Col num 1 is "TD"
Get col val 1
DECLARE
*
ERROR at line 1:
ORA-01007: variable not in select list
ORA-06512: at "SYS.DBMS_SQL", line 1854
ORA-06512: at line 22

oracle-database plsql
1个回答
0
投票

您错过了操作说明中的一个步骤;您尚未在第一个循环中调用

DEFINE_COLUMN
过程

...
BEGIN
  l_cursor_id := DBMS_SQL.OPEN_CURSOR;
  DBMS_SQL.PARSE( l_cursor_id, l_qry, DBMS_SQL.NATIVE );
  DBMS_SQL.DESCRIBE_COLUMNS( l_cursor_id, l_num_cols, l_cols_desc );
  l_status := DBMS_SQL.EXECUTE ( l_cursor_id );
  FOR idx IN 1 .. l_num_cols LOOP
    DBMS_OUTPUT.PUT_LINE( 'Col num ' || idx || ' is "' || l_cols_desc(idx).col_name || '"' );
    -- next line was missing
    DBMS_SQL.DEFINE_COLUMN( l_cursor_id, idx, l_col_val, 4000);
  END LOOP;
...

有了这个改变,它就可以工作并给出输出:

dbms_output:
Col num 1 is "TD"
 Get col val 1
 Value: 14-NOV-24

文档说要在

EXECUTE
之前这样做,但它似乎是双向的。

小提琴

© www.soinside.com 2019 - 2024. All rights reserved.