1

假设,我有一个包含查询字符串的字符串。

如何从 oracle 中的查询字符串中选择行?

我试过execute immediate了,但它什么也没返回。

declare 
    hello varchar(30000);
begin
    hello:='select * from test_table';
    execute immediate hello;    
end;
4

3 回答 3

4

您将使用动态游标。

这是一个例子SQL*Plus

SQL> var dyn_cur refcursor
SQL> DECLARE
  2     l_sql_query VARCHAR2(1000);
  3  BEGIN
  4     -- complex function that returns a query:
  5     l_sql_query := 'SELECT 1, dummy FROM dual';
  6     OPEN :dyn_cur FOR l_sql_query;
  7  END;
  8  /

PL/SQL procedure successfully completed.

SQL> print dyn_cur

         1 DUM
---------- ---
         1 X

您可以在 PL/SQL 过程和包中使用动态游标:

SQL> CREATE OR REPLACE PROCEDURE prc_dyn_cur(p_dyn_cursor OUT SYS_REFCURSOR) IS
  2  BEGIN
  3     OPEN p_dyn_cursor FOR 'SELECT 1, dummy FROM dual';
  4  END;
  5  /

Procedure created.

SQL> exec prc_dyn_cur(:dyn_cur);

PL/SQL procedure successfully completed.

SQL> print dyn_cur

         1 DUM
---------- ---
         1 X
于 2013-04-17T09:44:01.143 回答
1
declare 
    hello varchar(30000);
    type tb is table of test_table$rowtype;
    mytb tb;
begin
    hello:='select * from test_table';
    execute immediate hello bulk collect into mytb;
    -- now you got all og youe data in the "array" mytb
end;

请注意,此解决方案考虑到您知道要从哪个表中选择。另外,我认为您应该描述您要达到的目标。

于 2013-04-17T12:20:30.247 回答
0
CREATE OR REPLACE PROCEDURE query_executer (string_query IN VARCHAR)
IS
   c1 SYS_REFCURSOR;
   v_last_name employees.last_name%TYPE;    -- Selecting last_name
BEGIN
   OPEN c1 FOR string_query; -- Opening c1 for the select statement
   LOOP
      FETCH c1 INTO v_last_name;
      DBMS_OUTPUT.put_line (v_last_name);
      EXIT WHEN (C1%NOTFOUND);
   END LOOP;
END;

SET SERVEROUTPUT ON
EXECUTE query_executer('select last_name from employees');

输出

Procedure created.
Abel
Ande
Atkinso
PL/SQL procedure successfully completed.
于 2016-07-27T11:40:04.957 回答