Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ORACLE How to use spool with dynamic spool location

Ok, so i'm a complete newb with oracle. Now that that's out of the way;

I think you can get an understand of what i'm trying to do below. For each stored procedure found, output the DDL to a filename with it's name.

The problem is i can't figure out how to get the spool target to pick up the value of FileName which is being set by the cursor.

DECLARE 
objName varchar2(50);
FileName varchar2(50);

cursor curProcs is
    select OBJECT_NAME into objName
      FROM ALL_PROCEDURES WHERE OWNER = 'AMS' 
      ORDER BY OBJECT_NAME; -- get all procs in db
BEGIN
open curProcs;
  if curProcs%ISOPEN THEN
   LOOP
    FETCH curProcs into objName;
    EXIT WHEN curProcs%NOTFOUND;
    FileName := 'C:\ ' || objName || '.PRC.SQL';
    spool FileName; --BREAKS
     DBMS_METADATA.GET_DDL('PROCEDURE',objName);
    spool off;
   END LOOP;
  END IF;
END; 

Any ideas as to where i'm going wrong? and if anyone has an example of this i would appreciate it greatly.

I feel i must be dancing around it because if i create a column initially then

spool &ColName

i get a result, i just can't seem to dynmically change that &colname

Thanks for your help.

like image 588
Beta033 Avatar asked Dec 07 '22 06:12

Beta033


2 Answers

I found a better solution without the need to declare/begin/end code blocks or query statements.

A sample spool filename with the date and time can be achieved by:


sql> column dt new_value _dt 
sql> select to_char(sysdate,'ddMONyyyy_hh24mi') dt from dual; 
sql> spool &_dt
My file name:

27JUN2011_1727.lst

You can even specify the file extension if you need to (eg .txt). Just create another variable.

source: http://oracle.ittoolbox.com/groups/technical-functional/oracle-apps-l/variable-file-name-with-spool-1508529

like image 129
sanc Avatar answered Jan 05 '23 14:01

sanc


SPOOL is a SQLPlus directive and you can't mix it into the PL/SQL anonymous block. If you're going to do this purely in SQLPlus, I think the general idea would be to process in two passes, i.e. use a first script that dynamically generates the spool filename references into a second script that actually makes the dbms_metadata call.

[Edit]

This should be close to what you need - maybe a line termination problem, depending on your platform:

    set pagesize 0
    set linesize 300
    spool wrapper.sql
    select
    'spool '||object_name||'.sql'||chr(10)||
    'begin 
    dbms_metadata.get_ddl('||chr(39)||object_type||chr(39)||','||chr(39)||object_name||chr(39)||')'||' end;'||chr(10)||
    '/'||chr(10)||
    'spool off'
    from user_objects
    where object_type = 'PROCEDURE'
;
spool off
like image 29
dpbradley Avatar answered Jan 05 '23 14:01

dpbradley