pl / sql查询使用select语句插入多行

时间:2014-03-13 06:52:47

标签: for-loop plsql

我想在表格中插入多行。

查询将是:

insert into temp(table_name,run_date,table_count)
select 'TABLE_A',sysdate,count(*) from A;

insert into temp(table_name,run_date,table_count)
select 'TABLE_B',sysdate,count(*) from B;


insert into temp(table_name,run_date,table_count)
select 'TABLE_C',sysdate,count(*) from C;

如何使用pl / sql在循环中编写它?

谢谢, 安州

1 个答案:

答案 0 :(得分:0)

对于表的变量列表,这里是一个脚本,它读取指定所有者的Oracle系统表ALL_TABLES并将计数插入临时表。

DECLARE

  -- Define a cursor to get the list of tables you want counts for.
  cursor c1 is
  select table_name
  from all_tables
  where owner = 'YOUR_OWNER_HERE';

  -- Dynamically created select.
  stmt varchar2(200);

BEGIN

  -- The cursor for loop implicitly opens and closes the cursor.
  for table_rec in c1
  loop
    -- dynamically build the insert statement.
    stmt := 'insert into temp(table_name,run_date,table_count) ';
    stmt := stmt || 'select ''' || table_rec.table_name || ''','''|| sysdate||''','|| 'count(*) from ' || table_rec.table_name;

    -- Execute the insert statement.
    execute immediate(stmt);

  end loop;
END;  
commit;