Spooling from PL/SQL Block

Hi,
Is it possible to do spooling from a pl/sql block.The spool cannot be the first command because I want to give the spool file name in a loop and each time the spool name should change based on the value.
I tried all possiblities,but I couldn't can anyone give me some idea on how to do this.
I cannot use UTL_FILE option ,because the client agreed only for spooling.
Is it possible to write the spool data is excel format..
Please find below an example of my requirement..
DECLARE
CurSor Cur_Designation IS
Select Designation from tbl_Designation;
N_Desig Cur_Designation%RowType;
Cursor Cur_Emp(Desig Number) IS
Select Emp_no,Emp_name
From Employee Where Emp_Designation = Desig;
N_Emp Cur_Emp%RowType;
BEGIN
Open Cur_Designation ;
Loop
Fetch Cur_Designation INTO N_Desig;
EXIT WHEN Cur_Designation %NOTFOUND;
--Here I want to give the spool file name
Spool --Should be designation name
Open Cur_Emp(N_Desig.Designation);
Loop
Fetch Cur_Emp INTO N_Emp ;
EXIT WHEN Cur_Emp %NOTFOUND;
-- All employee details I need to come to log file
End Loop;
Close Cur_Emp;
End Loop;
Close Cur_Desingnation;
End;
Please advice me how to do this..
Thanks,
Bindu

<< I cannot use UTL_FILE option ,because the client agreed only for spooling. >>
<< I want to use it in a PL/SQL Block.I have some variables to declare and some cursors to be used.
So where should I use the spool command.
I tried to given after a fetch command ,but it is not working. >>
you can't use SPOOL inside PLSQL
you may use dbms_output calls in PLSQL
so create a procedure test2 instead of sqlscript test2 and you will be fine
rem =========== procedure test2 ================
create or replace
procedure test2 (p_param number) is
begin
             dbms_output.enable (1000000);
             dbms_output.put_line('A' || chr(9) || 'B' || chr(9) || 'C' ) ;
             FOR i_rec in (select a,b.c from xyz where a = p_param) LOOP
                 dbms_output.put_line (to_char(a) || chr(9) || b || chr(9) || c ) ;
             END LOOP ;
end ;
REM ====================================================                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

Similar Messages

  • Exec SQLPLUS command from PL/SQL Block

    Good Morning:
    How I can execute a SQLPLUS command (like SPOOL or DESCRIBE) from PL/SQL Block Procedure?:
    DECLARE
    BEGIN
    ls_command = 'DESCRIBE '||ls_table_name;
    EXECUTE SQLPLUS(ls_command);
    END;
    Thanks a lot for any idea.

    That's correct.
    However, in the case of the given example we can use DBMS_DESCRIBE package to get table descriptions. And we can use UTL_FILE to spool PL/SQL stuff to a file.
    Cheers, APC

  • Calling sql script from pl/sql block

    Hi
    I want to call a sql script from pl/sql block.
    like
    CREATE OR REPLACE procedure DataBaseExport(user_name in varchar2, pwd in varchar2)
    as
    begin
    execute immediate  '@ C:\Documents and Settings\umesh\emp.sql';
    end DataBaseExport;
    /

    Try something like this -
    CREATE OR REPLACE AND COMPILE JAVA SOURCE NAMED "Host" AS
    import java.io.*;
    public class Host
         public static void executeCommand(String command)
         try {
                String[] finalCommand;
                   if (isWindows())
                        finalCommand = new String[4];
                        // Use the appropriate path for your windows version.
                        finalCommand[0] = "C:\\windows\\system32\\cmd.exe"; // Windows XP/2003
                        //finalCommand[0] = "C:\\winnt\\system32\\cmd.exe"; // Windows NT/2000
                        finalCommand[1] = "/y";
                        finalCommand[2] = "/c";
                        finalCommand[3] = command;
                   else
                        finalCommand = new String[3];
                        finalCommand[0] = "/bin/sh";
                        finalCommand[1] = "-c";
                        finalCommand[2] = command;
              final Process pr = Runtime.getRuntime().exec(finalCommand);
             pr.waitFor();
             new Thread(new Runnable()
                public void run()
                      BufferedReader br_in = null;
                   try
                        br_in = new BufferedReader(new InputStreamReader(pr.getInputStream()));
                        String buff = null;
                        while ((buff = br_in.readLine()) != null)
                                  System.out.println("Process out :" + buff);
                               try {Thread.sleep(100); } catch(Exception e) {}
                        br_in.close();
                   catch (IOException ioe)
                        System.out.println("Exception caught printing process output.");
                        ioe.printStackTrace();
                 finally
                     try {
                              br_in.close();
                          } catch (Exception ex) {}
         ).start();
         new Thread(new Runnable()
           public void run()
                BufferedReader br_err = null;
                try
                   br_err = new BufferedReader(new InputStreamReader(pr.getErrorStream()));
                   String buff = null;
                   while ((buff = br_err.readLine()) != null)
                        System.out.println("Process err :" + buff);
                        try
                           Thread.sleep(100);
                         } catch(Exception e) {}
                   br_err.close();
               catch (IOException ioe)
                   System.out.println("Exception caught printing process error.");
                   ioe.printStackTrace();
              finally
                  try
                          br_err.close();
                   catch (Exception ex) {}
          ).start();
         catch (Exception ex)
                  System.out.println(ex.getLocalizedMessage());
      public static boolean isWindows()
              if (System.getProperty("os.name").toLowerCase().indexOf("windows") != -1)
              return true;
              else
              return false;
    CREATE OR REPLACE PROCEDURE Host_Command (p_command IN VARCHAR2)
    AS LANGUAGE JAVA
    NAME 'Host.executeCommand (java.lang.String)';
    --- THE PERMISSIONS ---
    call dbms_java.grant_permission('SYSTEM', 'SYS:java.io.FilePermission', '<<ALL FILES>>', 'read ,write, execute, delete');
    call dbms_java.grant_permission('SYSTEM', 'SYS:java.lang.RuntimePermission', 'writeFileDescriptor', '');
    call dbms_java.grant_permission('SYSTEM', 'SYS:java.lang.RuntimePermission', 'readFileDescriptor', '');And, finally,
    create or replace procedure call_sql_file(usr  in varchar2,
                                              pwd  in varchar2,
                                              host_str in varchar2)
    is
    begin
       host('sqlplus -s usr/pwd@host_str C:\UAX_Auto_Count.sql');
    exception
      when others then
        dbms_output.put_line(sqlerrm);
    end;Now, you can pass all the argument in order to execute that file.
    N.B.: Not Tested...
    Regards.
    Satyaki De.

  • Is it possible to call a windows batch file from PL/SQL block ??

    Hi gurus,
    Would require your help.Is it possible to call a windows batch file from PL/SQL block ??If yes can you give an example for the same or any workaround for the same.
    Regards
    Vijay

    You didn't specify a database version, but if you are 10g or higher, it's quite straightforward using an external job type in DBMS_SCHEDULER. Funnily enough i'm looking at something similar myself at the moment.
    Useful guide to some of the issues here Guide to External Jobs on 10g with dbms_scheduler e.g. scripts,batch files

  • Running sqlldr command from PL/SQL Block

    DECLARE
    BEGIN
    END;

    In SQL * plus we can run DOS commands using the following command
    HOST DIR
    HOST DIR/P
    But When we can't run the HOST command in PL/SQL Block..
    I have to Run sqlldr command from PL/SQL Block..
    i tried as follows
    DECLARE
    BEGIN
    EXECUTE IMMEDIATE ' host sqlldr control= bad= ';
    END;
    By
    BalaNagaRaju

  • How to call SQL script from PL/SQL block

    Hi All,
    I have a pl/sql block from which i need to call a *.sql script file.
    Please tell me that how can i do this?
    Thanks and Regards.

    > Though just for knowledge sake, would you please tell if there is a way
    to call a sql script from a pl/sql block.
    This question stems usually from a confusion about client-server and which is which in Oracle.
    SQL*Plus is a client. PL/SQL is a server side language. SQL is a server side language.
    When entering either one of these two languages in SQL*Plus (or TOAD, SQL-Developer, etc), the content is shipped to an Oracle server process, is parsed there, and is executed there.
    The Oracle server process servicing the client can accept a single SQL statement or PL/SQL block at a time.
    It cannot accept a block of SQL statements delimited with a semicolon. That is a client concept where the client will read each delimited statement and send that, one after the other (in synchronous call mode) to the Oracle server for execution.
    The Oracle server does not have a "script parser". It understands SQL. It understands PL/SQL. And that is what it expects from the client.
    Whether the client supports the SET command, the HOST command, SPOOL command, ability to run scripts, and so... have no bearing on what the server itself is capable of doing. The server does not care what feature set the client has. It is tasked with servicing the client via SQL and PL/SQL.
    It is not tasked to support or emulate client features like running SQL scripts.
    Nor confuse PL/SQL with the very limited command set of SQL*Plus. The two has nothing in common. And just as PL/SQL cannot understand C# or Delphi commands, it cannot understand SQL*Plus commands.

  • Display an Alert message from PL/SQL block in APEX

    Hi,
    we are getting an oracle exception while inserting a new row. As it is having the unique constaint on a coulumn.
    Now the problem iis we need to Display an "Alert message" based on the input field validation. That java script code for alert has to be embeded nside a PL/SQL block in Oracle APEX Application.
    we tried doing this with below code:
    Begin
    INSERT INTO <<table name>>(ID,NAME) VALUES (s1,:TXT_s2);
    exception when others then
    htp.p('<script language="javascript">');
    htp.p('alert("Exception");');
    htp.p('</script>');
    end;
    If anybody knows .... please reply.
    Thanks,
    Subarna

    If your end goal is showing a pretty error message instead of the message that the tables unique constraint raises try the following. This logic will show a nice message and not try to insert non-unique data.
    (1) Create a validation of type "Function Returning Error Text".
    (2) Place similar code like the following in your validation. Notice that if the unique name does not exist the no_data_found returns null allowing the validation to pass.
    DECLARE
      v_error varchar2(100);
    BEGIN
      SELECT 'A person by this name already exists.'
      INTO v_error
      FROM your_table
      WHERE your_name = :P1_YOUR_NAME;
      RETURN v_error;
    EXCEPTION
      WHEN no_data_found THEN
        RETURN NULL;
    END;

  • Error while invoking webservice using UTL_HTTP from PL/SQL Block

    Hi All,
    I am invoking a webservice (SOAP Request) from a PL/SQL block using UTL_HTTP package.
    I am able to send the complete request and am getting the required instance on the BPEL Console, but the process is erroring out while getting response back.
    and the PL/SQL Block is ending in error mentioned below:
    ERROR at line 1:
    ORA-29266: end-of-body reached
    ORA-06512: at "SYS.UTL_HTTP", line 1321
    ORA-06512: at "APPS.CSM_BPEL_TEST_PKG", line 34
    ORA-06512: at line 1
    Package is completing successfully if i test in local DB and local BPEL.
    But giving above error in client's.
    Can anyone let me know what is the cause of this.
    Thanks in advance

    I got it working by making process Synchronous.
    But with asynchronous process it is still same error.
    Thanks...

  • Displaying a Message from PL/SQL block to Java Application

    Hi
    How can One display or populate a message in Java Application, that is generated from a PL/SQL block?

    Well, the easiest option would be to have a "message" parameter that gets passed back from the PL/SQL block to the calling Java application.
    I'm guessing, though, that you wouldn't be asking the question if the easy solution was a viable option... If that's the case, you're going to have to describe the problem in a bit more detail...
    Justin

  • Export data into Excel from PL/SQL Block

    Hi,
    Please tell me how to export data into excel comming out from PL/SQL code in APEX.
    We can simply export data into excel if we have Report region, but my query is dynamic for which i had to use PL/SQL block. Now i want to export that data into excel.
    Thanks & Regards,
    Smith

    Hi,
    Take a look here http://spendolini.blogspot.com/2006/04/custom-export-to-csv.html
    Regards
    Paul

  • Call DLL from PL-SQL block

    Hello all,
    I want to call a function located in an external DLL from a PL-SQL block. I execute the followin steps :
    1. Create a database library pointing to the external DLL :
    create or replace library libstk as 'C:\SUMMIT\libstkdte_s_trade1.dll'
    2. Create the definition and the body package :
    CREATE OR REPLACE PACKAGE dllcall IS
         FUNCTION s_trade (
              s_in VARCHAR2 )
    RETURN VARCHAR2;
    PRAGMA RESTRICT_REFERENCES(s_trade, WNDS);
    end dllcall;
    show errors
    CREATE OR REPLACE PACKAGE BODY dllcall IS
    FUNCTION s_trade (s_in IN VARCHAR2) RETURN VARCHAR2
    IS EXTERNAL
    NAME "s_trade"
    LIBRARY libstk
    PARAMETERS (s_in           STRING,
    RETURN STRING);
    END dllcall;
    show errors
    set serveroutput on
    3. Start the PL-SQL block calling the external function. And I got the foolowing error :
    1 begin
    2 dbms_output.put_line ( dllcall.s_trade ( '<Request> ' ||
    3 '<CurveId>MYCURVE</CurveId> ' ||
    4 '<Mode>02</Mode> ' ||
    5 '<ExpCcy>GBP</ExpCcy> ' ||
    6 '<AsOfDate>20001023</AsOfDate> ' ||
    7 '<Entity>***SUMMIT-XML***</Entity> ' ||
    8 '</Request>') );
    9* end;
    10
    11 /
    begin
    ERROR à la ligne 1 :
    ORA-06520: PL/SQL: Error loading external library
    ORA-06522: Unable to load DLL
    ORA-06512: at "V31.DLLCALL", line 0
    ORA-06512: at line 2
    The "Read - Execute permissions" of the DLL file was given to "Authentified users" .
    What's wrong ?
    TIA
    PS : NT2K environment, DB 8.1.7
    R. Charles Emile

    Yes, a RPC was set up.
    Listner.ora
    LISTENER =
    (DESCRIPTION_LIST =
    (DESCRIPTION =
    (ADDRESS_LIST =
    (ADDRESS = (PROTOCOL = TCP)(HOST = Server1)(PORT = 1521))
    (ADDRESS_LIST =
    (ADDRESS = (PROTOCOL = NMP)(SERVER = Server1)(PIPE = ORAPIPE))
    (ADDRESS_LIST =
    (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC0))
    SID_LIST_LISTENER =
    (SID_LIST =
    (SID_DESC =
    (SID_NAME = PLSExtProc)
    (ORACLE_HOME = E:\Oracle\Ora81)
    (PROGRAM = extproc)
    tnsnames.ora
    extproc_connection_data =
    (DESCRIPTION =
    (ADDRESS_LIST =
    (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC0))
    (CONNECT_DATA = (SID = PLSExtProc))
    Thanks
    RCE

  • Get data from PL/SQL block and generate the data file in UNIX

    Hi All
    i was executing the following code block from Unix Shell Script. The following code was generating the file count_curdate.txt with all require infomrations. The query gives number of records , group by partition_dt
    ABC=`sqlplus -s <<EOF > count_curdate.txt
    uname/paswd@connectstring
    SET HEADING OFF;
    SELECT COUNT(*)||','||partition_dt from XYZ group by partition_dt;
    exit;
    END`
    But now i need to change the above code to use dbms_application_info.set_module in it. Could someone let me know how to generate the file using PL/SQL block in Shell Script. I tried writing following code, but it generate count_curdate.txt file with 0 bytes.
    ABC=`sqlplus -s <<EOF > count_curdate.txt
    uname/paswd@connectstring
    set serveroutput on;
    SET HEADING OFF;
    set feedback off;
    BEGIN
         dbms_application_info.set_module ('shm.ksh','get count by day');
         FOR reccur IN (SELECT COUNT(*)||','||partition_dt as "dcount" from XYZ group by partition_dt);
         LOOP
              DBMS_OUTPUT.PUT_LINE(reccur.dcount);
         END LOOP;
    end;     
    exit;
    END`

    OK, try this:
    ABC=`sqlplus -s <<EOF > count_curdate.txt
    uname/paswd@connectstring
    set serveroutput on;
    SET HEADING OFF;
    set feedback off;
    BEGIN
    dbms_application_info.set_module ('shm.ksh','get count by day');
    FOR reccur IN (SELECT COUNT(*)||','||partition_dt dcount from XYZ group by partition_dt);
    LOOP
    DBMS_OUTPUT.PUT_LINE(reccur.dcount);
    END LOOP;
    dbms_application_info.set_module (NULL,NULL);
    end;
    exit;
    EOF`Or this:
    ABC=`sqlplus -s <<EOF > count_curdate.txt
    uname/paswd@connectstring
    set serveroutput on;
    SET HEADING OFF;
    set feedback off;
    BEGIN
    dbms_application_info.set_module ('shm.ksh','get count by day');
    END;
    SELECT COUNT(*)||','||partition_dt dcount from XYZ group by partition_dt;
    BEGIN
    dbms_application_info.set_module (NULL,NULL);
    END;
    exit;
    EOF`Edited by: SeánMacGC on May 11, 2009 6:13 AM

  • FETCHING OUTPUT  VALUE FROM PL/SQL BLOCK

    hI aLL,
    I'm working on ODP.NET. I'm executing below pl/sql command. while executing this command in pl/sql it's showing the output which is an xml.
    declare
    xmloutput xmltype;
    xmldata varchar(32767);
    teid t_id := t_en_id( 'L','L',NULL,12121,'ABC','USER','N');
    tgetinfo to_info := NULL;
    RETVAL NUMBER;
    begin
    RETVAL := GET_DTLS(teid,tgetinfo);
    dbms_output.put_line(RETVAL);
    xmldata := tgetinfo.XML_info.getclobval();
    dbms_output.put_line(xmldata);
    end;
    I passed above command in string variable for passing in code. like below
    string StrQry = "";
    StrQry += "declare \n";
    StrQry += "xmloutput xmltype; \n";
    StrQry += "xmldata varchar(32767); \n";
    StrQry += "teid t_id := t_en_id( 'L','L',NULL,12121,'ABC','USER','N'); \n";
    StrQry += "tgetinfo to_info := NULL; \n";
    StrQry += "RETVAL NUMBER; \n";
    StrQry += "begin \n";
    StrQry += "RETVAL := GET_DTLS(teid,tgetinfo); \n";
    StrQry += "dbms_output.put_line(RETVAL); \n";
    StrQry += "xmldata := tgetinfo.XML_info.getclobval(); \n";
    StrQry += "dbms_output.put_line(xmldata); \n";
    StrQry += "end; \n";
    I'm passing output parameter ":temp" for this command. I want to catch output xml in ":temp" variable
    which is varchar2 type.
    Added below line before printing xmldata;
    StrQry += ":temp := xmldata; \n";
    cn.Open();
    OracleCommand cmd = new OracleCommand(StrQry, cn);
    cmd.Parameters.Add(":temp", OracleDbType.Varchar2, 32767, ParameterDirection.Output);
    cmd.ExecuteNonQuery();
    But which executing through c# code it's showing the below error.
    Oracle.DataAccess.Client.OracleException ORA-06502: PL/SQL: numeric or value err
    or: character string buffer too small
    ORA-06512: at line 11 at Oracle.DataAccess.Client.OracleException.HandleError
    Helper(Int32 errCode, OracleConnection conn, IntPtr opsErrCtx, OpoSqlValCtx* pOp
    oSqlValCtx, Object src, String procedure)
    at Oracle.DataAccess.Client.OracleException.HandleError(Int32 errCode, Oracle
    Connection conn, String procedure, IntPtr opsErrCtx, OpoSqlValCtx* pOpoSqlValCtx
    , Object src)
    at Oracle.DataAccess.Client.OracleCommand.ExecuteNonQuery()
    at orclGetDetails.Program.DoProcess()
    How can i get the output to output variable ":temp".
    Pls help.
    Ideas are appreciated.

    Your PL/SQL block isn't returning anything. DBMS_OUTPUT is, at best, a way of debugging code, not passing data around. Assuming you configure and enable an appropriately sized buffer, I suppose your ODP.Net application could make DBMS_OUTPUT.GET_LINE calls to retrieve the XML. But that's not not a way to design an application.
    If you want a PL/SQL block that returns XML, you'll need to create a function and have the function return the XML (you could also create a procedure with an OUT parameter in which you could return the XML).
    Justin

  • Javascript function call from PL/SQL block

    Hello,
    I am writing this pl/sql block that has checkbox and onselect, it calls javascript function.
    I defined javascript function in page header, even though I get error that says function is not defined.
    Please help.
    Thank you,
    H.

    I got it resolved...!!!

  • Call HOST cmd from PL/SQL Block

    Hi ,
    I'm trying to call the HOST command from stored procedure
    declare
    cmd varchar2(100):='c:\file.bat';
    begin
    execute immediate 'host('c:\file.bat')';
    dbms_output.put_line('Executed');
    end;
    but,It gives an error msg on execute immediate stmt.
    Plz resolve this problem.
    Rgrds,
    Anand

    You are confusing SQL*Plus's command (a client) with that of PL/SQL.
    Just as you cannot code C# commands, or Perl commands, or PHP commands in PL/SQL, you cannot code SQL*Plus commands in PL/SQL.
    SQL*Plus runs on your client platform. It has a couple of commands.
    PL/SQL is a server side programming language. This runs inside the Oracle server process servicing the client.
    This server process does not know your client language commands. Nor can this server process hack across the network, break into your computer, and access your local file called c:\file.bat.
    Yes, you can execute server o/s commands and execute server programs from PL/SQL via a Java stored procedure or via the EXTPROC interface. Refer to the sample code in [url http://forums.oracle.com/forums/thread.jspa?messageID=1439836#1439836]this thread on how to call server o/s commands and server programs.

Maybe you are looking for