Sql – counting rows from a cursor in pl/sql

oraclesql

I'm trying to count the number of rows that will be returned from an sql statement . This statement is in a cursor

My code is like this

DECLARE

v_counter int := 0 ;

select count(*) into v_counter from (
cursor get_sth is select * from table1 where condit..) ;


BEGIN

DBMS_OUTPUT.PUT_LINE (v_counter);


END ;
/

and it doesn't work

Is there any other solution that makes me counting the number of rows of a cursor result , I'm really noob

thanks helpers

Best Answer

If your aim is to reuse an existing cursor definition and not have to repeat the query it's based on, you could loop over its results to get a count:

set serveroutput on
declare
  v_counter pls_integer := 0;
  cursor get_sth is select * from all_tables where owner = user; -- your query
begin
  for sth in get_sth loop
    v_counter := v_counter + 1;
  end loop;
  dbms_output.put_line (v_counter);
end;
/

You can't count the rows in the result set without fetching them, which the cursor loop does. (@MarcinWroblewski shows another way to that, with explicit fetches). Either way the cursor is consumed by the process. If you want to do anything with the returned data after counting it you'd have to re-execute and re-fetch the cursor.