使用现有代码创建Oracle存储过程

时间:2013-04-08 11:47:39

标签: sql oracle procedure

我有以下脚本,我在oracle中运行以返回一些数据,但是我想将它存储为存储过程,所以我不必在运行时重新运行这一整段代码。如果有人能让我知道如何做到这一点,我将非常感激。我一直在尝试,但没有太多运气。

以下是我想从存储过程运行的代码。

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;

3 个答案:

答案 0 :(得分: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;
/

然后执行以下程序: -

execute procedure_name;

答案 1 :(得分:1)

作为ref游标的替代方法,您可以使用流水线函数(在某些SQL客户端中更容易使用):

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;
/

可以按以下方式使用:

select *
from table(get_trains());

答案 2 :(得分:0)

您需要游标在oracle中选择数据。有关详细信息,请参阅链接Oracle – Returning a recordset from a stored procedure

-- 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