执行变量抛出错误

时间:2013-08-23 11:33:44

标签: oracle plsql execute-immediate

我正在创建一个plslq程序。因为查询需要根据指定的表名动态生成。我能够在变量中生成查询。我的问题是如何使用plsql在变量中执行查询。执行/执行立即在这里不起作用。

    DECLARE
      f UTL_FILE.FILE_TYPE;
      s VARCHAR2(200);
      c number:=0;
    query varchar(32767);
    BEGIN
--Reading and getting the value from a text file. The text file contains lot of table names
       f := UTL_FILE.FOPEN('DATADIR_EXP1','Table.txt','R');
      LOOP
       UTL_FILE.GET_LINE(f,s);
       DBMS_OUTPUT.PUT_LINE(s);
       IF C <> 0 THEN
       query := query || ' UNION ALL';
       END IF;
--Query is generated here.
       query := query || ' SELECT '''||s||''' AS TABLE_NAME,MIn(Updated_Time) AS MIN_VALUE,MAX(Updated_Time) AS MAX_VALUE,count(*) AS NUMBER_OF_ROWS FROM ' || s ;
       c:=c+1;
      END LOOP;
     EXCEPTION
        WHEN NO_DATA_FOUND THEN
             UTL_FILE.FCLOSE(f);
             DBMS_OUTPUT.PUT_LINE('Number of lines: ' || c);
    DBMS_OUTPUT.PUT_LINE(query);
-- The problem is here. Execute / Execute Immediate is not working.
    EXECUTE IMMEDIATE(query);
             UTL_FILE.FCLOSE(f);
    END;
    /

如何完成此任务。我只需要执行查询。

1 个答案:

答案 0 :(得分:0)

您需要将SELECT语句的输出列绑定到某些输出变量。否则,您只是执行该语句,并且不返回任何内容。这是一个例子:

DECLARE
   v1   NUMBER (10);
   v2   VARCHAR2 (20);
BEGIN
   EXECUTE IMMEDIATE 'select 1, ''hello'' from dual' INTO v1, v2;

   DBMS_OUTPUT.put_line ('v1 = ' || v1);
   DBMS_OUTPUT.put_line ('v2 = ' || v2);
END;

(输出)

v1 = 1
v2 = hello

这仅在您返回一行时才有效。如果查询返回多行,则需要将结果打开到游标中。例如:

DECLARE
   TYPE EmpCurTyp IS REF CURSOR;  -- define weak REF CURSOR type
   emp_cv   EmpCurTyp;  -- declare cursor variable
   my_ename VARCHAR2(15);
   my_sal   NUMBER := 1000;
BEGIN
   OPEN emp_cv FOR  -- open cursor variable
      'SELECT ename, sal FROM emp WHERE sal > :s' USING my_sal;
   ...
END;

请参阅oracle documentation