我想根据行(行号)获取记录。我已经完成了使用sql查询本身。
select * from (select m.*,rownum r from employees m) where r between 80 and 100
但是现在我想在存储过程(oracle)中使用游标来获取相同的东西来获取80和100之间的记录(基于rownum伪列)。任何人都可以帮助我吗?
答案 0 :(得分:0)
您可能需要查看Stored Procedures和Cursors才能了解基本知识。除此之外,您的查询可以很容易地包含在游标和过程中。如果您打算使用显式游标,它可能是这样的:
CREATE OR REPLACE stored_procedure_name AS
CURSOR IS
select * from (select rownum r,salary from employees) where r between 80 and 100;
BEGIN
open c1;
loop
fetch c1
into a,b;
dbms_output.put_line(a || b);
exit when c1%notfound;
end loop;
close c1;
END;
答案 1 :(得分:0)
您可以使用简化的语法,避免直接处理游标。我认为这种方式不易出错。
示例:
begin
for rec in (
select rn, salary
from (
select rownum as rn, salary
from employees
) where rn between 80 and 100
) loop
dbms_output.put_line(to_char(rec.rn) || rec.salary);
end loop;
end;
/
文档:Query Result Set Processing With Cursor FOR LOOP Statements
修改强>
这种结构的一般形式是:
begin
for rec in (
select * from employees -- write any SQL you want here
) loop
-- do whatever you need to do inside the loop...
-- you can access the results of the query through the "rec" variable.
dbms_output.put_line(rec.column1);
dbms_output.put_line(rec.column2);
dbms_output.put_line(rec.column3);
end loop;
end;
/
答案 2 :(得分:0)
您可以使用像bellow
这样的简单构造declare
v_e_row employees%rowtype; --employees table row type
v_rownum number;
begin
for emp in (select * from (select m.* , rownum r from employees m) where r between 80 and 100)
loop
v_e_row.emp_id := emp.emp_id; -- sample value ( you will get all value including rownum)
v_rownum := emp.r;
dbms_output.put_line(v_e_row.emp_id||v_rownum);
end loop;
end;