2016-06-10 43 views
0

我有一個運行良好delete_import.bat文件下,它有如下內容:如何生成SQL腳本的日誌從批處理文件運行

sqlplus @C:\Exp_Imp_Util\delete_tmc.sql 

的deletetmc.sql文件的內容,我希望所有的數據庫對象刪除。但是現在每當我運行批處理文件時,它應該創建所有刪除語句的日誌,並且如果在刪除sql語句時發生任何oracle錯誤,它也應該寫入日誌文件。

CONNECT TMC/TMC; 
spool off 
declare 
stringa varchar2(100); 

cursor cur is 
select * 
from user_objects; 

begin 
for c in cur loop 
begin 
stringa := ''; 

if c.object_type = 'VIEW' then 

stringa := 'drop view ' || c.object_name; 
EXECUTE immediate stringa; 

elsif c.object_type = 'TABLE' then 

stringa := 'drop table ' || c.object_name || ' cascade constraints'; 
EXECUTE immediate stringa; 

elsif c.object_type = 'SEQUENCE' then 

stringa := 'drop sequence ' || c.object_name; 
EXECUTE immediate stringa; 
elsif c.object_type = 'PACKAGE' then 

stringa := 'drop package ' || c.object_name; 
EXECUTE immediate stringa;  

elsif c.object_type = 'TRIGGER' then 

stringa := 'drop trigger ' || c.object_name; 
EXECUTE immediate stringa;  

elsif c.object_type = 'PROCEDURE' then 

stringa := 'drop procedure ' || c.object_name; 
EXECUTE immediate stringa; 

elsif c.object_type = 'FUNCTION' then 

stringa := 'drop function ' || c.object_name; 
EXECUTE immediate stringa;  
elsif c.object_type = 'SYNONYM' then 

stringa := 'drop synonym ' || c.object_name; 
EXECUTE immediate stringa; 
elsif c.object_type = 'INDEX' then 

stringa := 'drop index ' || c.object_name; 
EXECUTE immediate stringa; 
elsif c.object_type = 'PACKAGE BODY' then 

stringa := 'drop PACKAGE BODY ' || c.object_name; 
EXECUTE immediate stringa;  

end if; 

    exception 
when others then 
null; 
end; 
end loop; 
-- PURGE recyclebin 

end; 
/
EXIT; 

回答

3

您可以設置SPOOL寫入一個文件,然後使用DBMS_OUTPUT

script.sql

spool spool.txt 
set serveroutput on 
declare 
    vSQL varchar2(1000); 
begin 
    vSQL := 'create table tab1 (a number)'; 
    begin 
     execute immediate vSQL; 
     dbms_output.put_line('OK - ' || vSQL); 
    exception 
    when others then 
     dbms_output.put_line('KO - ' || vSQL || ' - ' || sqlerrm);   
    end; 

    vSQL := 'drop table tab1'; 
    begin 
     execute immediate vSQL; 
     dbms_output.put_line('OK - ' || vSQL); 
    exception 
    when others then 
     dbms_output.put_line('KO - ' || vSQL || ' - ' || sqlerrm);   
    end; 

    vSQL := 'drop table tab1'; 
    begin 
     execute immediate vSQL; 
     dbms_output.put_line('OK - ' || vSQL); 
    exception 
    when others then 
     dbms_output.put_line('KO - ' || vSQL || ' - ' || sqlerrm);   
    end; 
end; 
/ 
spool off 

運行腳本,文件spool.txt後將是:

OK - create table tab1 (a number)            
OK - drop table tab1                
KO - drop table tab1 - ORA-00942: table or view does not exist     

PL/SQL procedure successfully completed. 
+0

我試過了,但在日誌文件中顯示爲Connected。爲了測試,我創建了一個表並試圖從這個批處理文件中刪除它。該表被刪除,但在日誌文件中寫爲已連接。沒有關於哪個表被刪除的信息。 – Andrew

+0

也許你把CONN放在了錯誤的地方;嘗試在任何其他聲明之前移動它 – Aleksej

相關問題