2014-03-13 84 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;