我有一个FOR LOOP游标,在遍历它时,我需要从游标中删除某些行,但不能从数据库表中删除。那有可能吗?
我要完成的工作是,通过删除满足特定条件的每个处理过的行,只剩下我的代码未处理的游标中的那些行
答案 0 :(得分:0)
在读取游标时无法修改它;如果要排除行,则在生成游标时需要这样做。
使用WHERE
子句从游标中排除行:
DECLARE
OPEN cursor_name FOR
SELECT *
FROM my_table
WHERE primary_key_column NOT IN ( 1, 2, 3 ); -- criteria to exclude.
BEGIN
-- process cursor with excluded rows.
END;
/
答案 1 :(得分:0)
使用查询的结果加载一个集合,确保该集合包含初始化为False的“已处理”标志。然后遍历集合,根据需要进行处理。完成后将标志翻转为True。
然后,您可以再次遍历该集合,其中处理的标记为False,以获取未触及的行。
答案 2 :(得分:0)
将光标行批量收集到一个集合中。然后在处理的每一行中将其从集合中删除。剩下的将是最初未处理的行。下面提供了所需过程的框架:
declare
cursor c_cursor
is
select ... ;
type c_cursor_t is table of c_cursor%rowtype;
l_cursor_data c_cursor_t;
l_cursor_indx integer;
begin
open c_cursor;
fetch c_cursor
bulk collect
into l_cursor_data;
close c_cursor;
l_cursor_indx := l_cursor_data.first; -- set collection index to 1st value
while l_cursor_indx is not null
loop
if <row should be processed> -- determine which rows to process
then
<process_row>; -- and process them
l_cursor_data.delete(l_cursor_indx); -- then delete processed rows
end if ;
l_cursor_indx := l_cursor_data.next(l_cursor_indx); -- set collection index to next row or null if no morw rows.
end loop;
--- Handle anything left in l_cursor_data collection as they have not been processed.
--- THE SAME LOOP STRUCTURE AN BE USED FOR THE COLLECTION IF NEEDED.
end ;
当然,与@ MT0一样,从一开始就消除那些不会被处理的内容会容易得多。仅检索要处理的行始终是最佳实践。