Oracle: Dynamic SQL

前端 未结 1 1471
我寻月下人不归
我寻月下人不归 2020-12-22 08:24

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

相关标签:
1条回答
  • 2020-12-22 08:43

    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 (;).

    0 讨论(0)
提交回复
热议问题