2

I have a query

select * from myTable

...and I want to wrap this query inside a stored procedure, and have the store procedure output the results of this query.

How do I do it?

In ms-sql, i can store my query as a string to a string variable. And then do "Execute (variable)". Why no such thing in Oracle?

1
  • @Saobi: I updated my answer to include examples of dynamic SQL in a sproc, incl using bind variables (though I recommend using CONTEXT instead for most cases).
    – OMG Ponies
    Commented Oct 14, 2009 at 21:17

3 Answers 3

6

Use:

CREATE OR REPLACE PROCEDURE MY_SPROC() RETURN SYS_REFCURSOR

L_CURSOR SYS_REFCURSOR;

BEGIN

  OPEN L_CURSOR FOR 
    SELECT * from MYTABLE;

  RETURN L_CURSOR;

END;

Use this if you want to run dynamic SQL on Oracle:

CREATE OR REPLACE PROCEDURE MY_SPROC() RETURN SYS_REFCURSOR

L_CURSOR SYS_REFCURSOR;
L_QUERY  VARCHAR2(5000) DEFAULT 'SELECT ...';

BEGIN

  OPEN L_CURSOR FOR L_QUERY;
  RETURN L_CURSOR;

END;

If you want to include bind variables in the dynamic SQL:

CREATE OR REPLACE PROCEDURE MY_SPROC() RETURN SYS_REFCURSOR

L_CURSOR SYS_REFCURSOR;
L_QUERY  VARCHAR2(5000) DEFAULT 'SELECT ...';

BEGIN

  OPEN L_CURSOR FOR L_QUERY
   USING bind_var1;
  RETURN L_CURSOR;

END;
4
  • Why so complicated? If i can run this query plainly, why is it so much more complicated to run it from stored procedure?
    – Saobi
    Commented Oct 14, 2009 at 20:43
  • Having a query stored in a procedure makes it easier to maintain, change and improve.
    – OMG Ponies
    Commented Oct 14, 2009 at 20:47
  • I don't see the part about outputting the results?
    – Rob
    Commented Oct 14, 2009 at 22:33
  • @Rob: There are two options for exposing query results outside a procedure or function - return object datatype, or OUT parameter. But with either case, they have to be the SYS_REFCURSOR/REFCURSOR datatype when dealing with 2+ column/values in a single variable reference.
    – OMG Ponies
    Commented Oct 14, 2009 at 23:23
0

You need to use a ref cursor.

Check out the odp documentation. It has a very good example, covering both the DB and the .Net code.

It comes with the installation of the oracle client, but it is hidden deep in the directory structure. Go to the -> odp -> doc -> .

0

Ref Cursors have been the standard way of doing this for years, but there is a slightly different alternative using pipelined table functions: http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/tuning.htm#sthref2345

They are fairly widely used in data warehousing applications and the execution can be parallelised so they're very high performance (not as good as just running a SELECT though).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.