2014-03-13 57 views
0

我想将多行插入到表中。使用select语句插入多行的pl/sql查询

的查询是:

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的循环?

感谢, 安居房

+0

为什么你需要一个循环?为什么不'UNION'三个查询并立即插入? –

+0

如果你不想硬编码A,B,C,你需要使用动态sql(EXECUTE IMMEDIATE)。 –

回答

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;