我正在创建一个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;
/
如何完成这项任务。我只需要执行查询。
您需要将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文档