0

I have the following script which i run inside oracle to return some data, however I want to store this as a stored procedure so I don't have to keep re-running this whole bit of code at run time. If anyone can let me know how to do this, I would be very grateful. I've been experimenting already but not had much luck.

Below is the code I want to run from the stored procedure.

SET SERVEROUTPUT ON;
declare 
cursor c_emp is
select *
from train;
r_emp c_emp%ROWTYPE;
begin
open c_emp;
loop
fetch c_emp into r_emp;
exit when c_emp%NOTFOUND;
DBMS_OUTPUT.put_line(r_emp.trainid);
end loop;
close c_emp;
end;
2
  • You need the result as result set right?
    – TechDo
    Apr 8, 2013 at 11:50
  • Thanks all for your suggestions. Very helpful indeed.
    – Reidacus
    Apr 8, 2013 at 12:20

3 Answers 3

1
create or replace procedure procedure_name
is
begin
declare 
cursor c_emp is
select *
from train;
r_emp c_emp%ROWTYPE;
begin
open c_emp;
loop
fetch c_emp into r_emp;
exit when c_emp%NOTFOUND;
DBMS_OUTPUT.put_line(r_emp.trainid);
end loop;
close c_emp;
end;
end procedure_name;
/

then just execute the procedure by :-

execute procedure_name;
0
1

As an alternative to a ref cursor, you can use a pipelined function (which is easier to use in some SQL clients):

create type id_list as table of integer
/

CREATE OR REPLACE function get_trains
  return id_list
  pipelined
as
begin  
  for train_rec in (select trainid from train) loop
    pipe row (train_rec.trainid);
  end loop;
  return;
end;
/

This can be used in the following manner:

select *
from table(get_trains());
0

You need cursor to select data in oracle. Please refer the link Oracle – Returning a recordset from a stored procedure for more details.

-- Create package
CREATE OR REPLACE PACKAGE types
AS
type cursorType is ref cursor;
END;

-- Here we have declared cursor variable of type cursorType as an output variable.
CREATE OR REPLACE PROCEDURE SP_SELECT_DATA
(
  p_ResultSet        OUT  TYPES.cursorType
)
AS
BEGIN
  OPEN p_ResultSet FOR
  select * from your_table;
END SP_SELECT_DATA;

--Testing
VARIABLE resultSet  REFCURSOR
EXEC SP_SELECT_DATA(:resultSet);
PRINT :resultSet

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.