Skip to Main Content

Breadcrumb

Question and Answer

Tom Kyte

Thanks for the question, Johny.

Asked: October 18, 2007 - 6:47 am UTC

Last updated: February 07, 2011 - 6:55 am UTC

Version: 10.0.2

Viewed 50K+ times! This question is

You Asked

Tom,

See the code below.

why did my second output display 1? Which is not correct. I was
expecting 2.

In the first output part it displays correctly as 2.

Any explanation would be appreciated.

Thanks in advance
Johny Alex




Create table test_case (col1 varchar2(10));

set serveroutput on

declare
l_sql varchar2(1000);
begin

l_sql := 'insert into test_case (col1) select ''1'' from dual union all select ''2'' from dual
';

execute immediate l_sql;

-- 1st output comes here
dbms_output.put_line('Rows = '||TO_CHAR(SQL%ROWCOUNT));

execute immediate 'BEGIN '||l_sql||'; END;';

-- second output comes here
dbms_output.put_line('PLSQL Rows = '||TO_CHAR(SQL%ROWCOUNT));

end;

/


and Tom said...

because sql%rowcount is in regards to the last thing executed by execute immediate. In your case, that was a plsql block, which set it to "one"

ops$tkyte%ORA9IR2> begin
  2    dbms_output.put_line('PLSQL Rows = '||TO_CHAR(SQL%ROWCOUNT));
  3    execute immediate 'begin null; end;';
  4    dbms_output.put_line('PLSQL Rows = '||TO_CHAR(SQL%ROWCOUNT));
  5  end;
  6  /
PLSQL Rows =
PLSQL Rows = 1

PL/SQL procedure successfully completed.


This will work for you - you need to access sql%rowcount IMMEDIATELY after the sql in question:

ops$tkyte%ORA9IR2> declare
  2    l_sql varchar2(1000);
  3    l_cnt number;
  4  begin
  5
  6    l_sql := 'insert into test_case (col1) select ''1'' from dual union all select ''2'' from dual ';
  7
  8    execute immediate l_sql;
  9
 10  -- 1st output comes here
 11    dbms_output.put_line('Rows = '||TO_CHAR(SQL%ROWCOUNT));
 12
 13    execute immediate 'BEGIN '||l_sql||'; END;';
 14  -- second output comes here
 15    dbms_output.put_line('PLSQL Rows = '||TO_CHAR(SQL%ROWCOUNT));
 16<b>
 17    execute immediate 'begin ' || l_sql || '; :x := sql%rowcount; end;' using OUT l_cnt;
 18    dbms_output.put_line('Returned Rows = '||l_cnt);</b>
 19  end;
 20  /
Rows = 2
PLSQL Rows = 1
Returned Rows = 2

PL/SQL procedure successfully completed.



Rating

  (1 rating)

Is this answer out of date? If it is, please let us know via a Comment

Comments

Session rowcount

Alex, February 07, 2011 - 5:21 am UTC

Does Oracle has a function that returns counter for session affected rows or some V$ view that shows total affected rows in a session?

Tom Kyte
February 07, 2011 - 6:55 am UTC

no, not that I'm aware of. This information is available on a per statement basis (sql%rowcount in plsql, available via other methods in various API's).

More to Explore

PL/SQL demos

Check out more PL/SQL tutorials on our LiveSQL tool.

PL/SQL docs

PL/SQL reference manual from the Oracle documentation library