Sql Oracle中循环的游标
请告诉我如何在oracle中使用循环游标 如果我使用下一个代码,一切都很好Sql Oracle中循环的游标,sql,oracle,for-loop,plsql,cursor,Sql,Oracle,For Loop,Plsql,Cursor,请告诉我如何在oracle中使用循环游标 如果我使用下一个代码,一切都很好 for rec in (select id, name from students) loop -- do anything end loop; 但如果我为这个sql语句定义变量,它就不起作用了 v_sql := 'select id, name from students'; for rec in v_sql loop -- do anything end loop; 错误:PLS-00103用于
for rec in (select id, name from students) loop
-- do anything
end loop;
但如果我为这个sql语句定义变量,它就不起作用了
v_sql := 'select id, name from students';
for rec in v_sql loop
-- do anything
end loop;
错误:PLS-00103用于解决与问题中第二种方法相关的问题,您需要使用 游标变量和打开游标并获取数据的显式方式。事实并非如此 允许在
FOR
循环中使用光标变量:
declare
l_sql varchar2(123); -- variable that contains a query
l_c sys_refcursor; -- cursor variable(weak cursor).
l_res your_table%rowtype; -- variable containing fetching data
begin
l_sql := 'select * from your_table';
-- Open the cursor and fetching data explicitly
-- in the LOOP.
open l_c for l_sql;
loop
fetch l_c into l_res;
exit when l_c%notfound; -- Exit the loop if there is nothing to fetch.
-- process fetched data
end loop;
close l_c; -- close the cursor
end;
试试这个:
cursor v_sql is
select id, name from students;
for rec in v_sql
loop
-- do anything
end loop;
然后无需
打开
,获取
或关闭
光标。如果在运行时进行查询,则必须使用Refcursor。实际上,refcursors是指向查询的指针,它们不会占用获取的行的任何空间。
普通的游标将不适用于它
declare
v_sql varchar2(200);
rec sys_refcursor;
BEGIN
v_sql := 'select id, name from students';
open rec for v_sql
loop
fetch
exit when....
-- do anything
end loop;
您没有在任何地方执行该sql字符串。就这么做吧
v_sql := 'select id, name from students';
open cur for v_sql;
for rec in cur loop
-- do anything
end loop;
或者你可以这样做
cursor cur is select id, name from students;
open cur;
for rec in cur loop
-- do anything
end loop;
for rec in (select id, name from students) loop
-- do anything
end loop
或者你可以这样做
cursor cur is select id, name from students;
open cur;
for rec in cur loop
-- do anything
end loop;
for rec in (select id, name from students) loop
-- do anything
end loop
我认为,如果我知道定义阶段的sql代码,那么这段代码会起作用,但它会在执行阶段生成。您可以在游标定义中定义参数,但只能为where子句定义参数。如果您需要动态设置表,那么
openc FOR string
可能是最好的选择。目前最合适的答案。我想,一切都会变得容易。谢谢你的决定。