我是Oracle和数据库的新手。
我试图用游标编写存储过程。如何在游标循环中编写select语句,如何遍历从游标循环中的select中得到的结果集?
例如:
Open Curs1;
Exit When Curs1%NotFound;
Loop
Select column1,column2 from table -- Returns multiple records. How to loop through this record set and perform CRUD operations.
End loop;
Close Curs1;
答案 0 :(得分:2)
使用FOR循环游标 - 它们比打开/获取/关闭语法更快更简单。
begin
for results1 in
(
select ...
) loop
--Do something here
for results2 in
(
select ...
where some_table.some_column = results1.some_column
) loop
--Do something here
end loop;
end loop;
end;
/
虽然这确实回答了这个问题,但你通常不希望像这样在循环内部循环。如果可能的话,最好将两个SQL语句与一个连接组合,然后遍历结果。
答案 1 :(得分:0)
您需要在循环中声明CURSOR
和FETCH
记录。
DECLARE
CURSOR curs1
IS
SELECT column1,
column2
FROM yourtable;
v_column1 yourtable.column1%TYPE;
v_column2 yourtable.column2%TYPE;
BEGIN
OPEN curs1;
LOOP
FETCH curs1
INTO v_column1,
v_column2;
EXIT
WHEN curs1%NOTFOUND;
INSERT INTO yourtable2(col1)VALUES( '000'||v_column1 );
-- A sample DML operation.
--Do other operations on individual records here.
END LOOP;
CLOSE curs1;
END;
答案 2 :(得分:0)
尝试使用以下示例,从游标变量emp_cv一次一行地获取行到用户定义的记录emp_rec:
declare
TYPE YourType IS ref cursor return YourTable%rowtype;
tab_cv YourType;
tab_rec YourTable%rowtype;
begin
loop
fetch tab_cv into emp_rec;
exit when tab_cv%notfound;
...
end loop;
end;
BULK COLLECT子句允许您一次从结果集或整个结果集中获取整个列。以下示例将游标中的列检索到集合中:
declare
type NameList IS table of emp.ename%type;
names NameList;
cursor c1 is select ename from emp where job = 'CLERK';
begin
open c1;
fetch c1 bulk collect into names;
...
close c1;
end;
以下示例使用LIMIT子句。对于循环的每次迭代,FETCH语句将100行(或更少)读取到索引表acct_ids中。之前的值将被覆盖。
declare
type NumList is table of number index by binary_integer;
cursor c1 is select acct_id from accounts;
acct_ids NumList;
rows natural := 100; -- set limit
begin
open c1;
loop
/* The following statement fetches 100 rows (or less). */
fetch c1 bulk collect into acct_ids limit rows;
exit when c1%notfound;
...
end loop;
close c1;
end;