1

I am trying to write Oracle dynamic SQL to do row count, below is my approach, please help me complete.

This is my select to generate the individual count statements:

select 'select count(*) from '||table_name||';'
from dba_tables
where owner = 'URR';

This is how I started:

declare
 l_owner varchar2(30) := 'URR';
 l_table_name varchar2(30);
 l_columns varchar2(32000);
 l_sql varchar2(32000);
begin
Alex Poole
192k11 gold badges198 silver badges349 bronze badges
asked May 1, 2013 at 14:50
1

1 Answer 1

3

Here's a simple example that looks at tables in your own schema:

set serveroutput on
declare
 c number;
begin
 for r in (select table_name from user_tables) loop
 execute immediate 'select count(*) from ' || r.table_name
 into c;
 dbms_output.put_line(r.table_name ||': '|| c);
 end loop;
end;
/

To look at someone else's tables you'll need to use dba_tables as you started to try, or more likely all_tables as that should exclude tables you can't count from, but you'll also need to specify the owner in the count statement.

Normally you'd want to use bind variables to avoid SQL injection, but you have to specify object names with concatenation like this.

Something else to look out for is a mistake you had in your query, but which Egor has now removed from the question. The dynamic SQL string you execute should not be terminated by a semicolon (;).

answered May 1, 2013 at 15:15
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.