1

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;
1
  • Firstly, you'd really try to avoid needing to do something like that. Commented Apr 17, 2013 at 10:25

3 Answers 3

4

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
Sign up to request clarification or add additional context in comments.

1 Comment

@hsuk, why not something like this sqlquery.com/php_oracle_ref_cursor.htm
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;

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.

Comments

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

OUTPUT

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.