hsuk
hsuk

Reputation: 6860

How to select from query string in oracle

Lets assume, I have a string that holds a query string.

How can I select the rows from that query string in oracle ?

I tried execute immediate but it returns nothing.

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

Upvotes: 1

Views: 17220

Answers (3)

Pirate X
Pirate X

Reputation: 3095

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');

OUTPUT

Procedure created.
Abel
Ande
Atkinso
PL/SQL procedure successfully completed.

Upvotes: 0

haki
haki

Reputation: 9759

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;

notice that this solution takes into account that you know what table you are selecting from. plus, i think you should describe what exactly it is you are trying to achieve.

Upvotes: 1

Vincent Malgrat
Vincent Malgrat

Reputation: 67722

You would use a dynamic cursor.

Here's an example with 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

You can use dynamic cursors in PL/SQL procedures and packages:

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

Upvotes: 4

Related Questions