Using spool in a procedure

Hi,
I've a package with 6 procedures.
In one procedure I need to load the data into a flat file. The procedure contains only one select statement.
example:
procedure pro_test as
select * from emp;
end pro_test;
Shell script is being used to call one procedure inside the package and that procedure is calling remaining procedures inside it.
connected to database using sqlplus.
Can anyone help me out how I can spool the select statement inside the procedure. Version of oracle is 11g.

Hi,
Why do you want to do
SELECT  *
FROM    table_name;
inside the procedure?  Why not have your script run the procedure (without the query above), and then do that query afterwards, when you can use SPOOL to put the results in a file?
If you really must write a file from a procedure, here's an example of how to use utl_file.
First, SYSTEM (or some other user with the CREATE ANY DIRECCTORY system privilege) must create a directory, and grant privileges to use it.  For example:
CREATE OR RPLEACE DIRECTORY  a_dir  AS 'C:\Foo\A_Folder';
GRANT ALL ON DIRECTORY  a_dir  TO PUBLIC;
Typically, SYSTEM does this once, and other people use it hundreds of times.
You might create a file in that directory like this:
CREATE OR REPLACE PROCEDURE  write_dept
IS
    f  utl_file.file_type;
BEGIN
    f := utl_file.fopen ('A_DIR', 'Dept.txt', 'W');
    FOR  r  IN  (  SELECT  *
                   FROM    scott.dept
    LOOP
        utl_file.put_line ( f
                          , TO_CHAR (r.deptno, 'FM00')
                            || ' '
                            || RPAD (r.dname, 15)
                            || r.loc
    END LOOP;
    utl_file.fclose (f);
END  write_dept;
SHOW ERRORS

Similar Messages

  • Report using spool in Russian

    Hey SAPians,
    i am stuck here with an issue. i am trying to print a report using spool in Russian, its status ends in error. however when i try printing same in english its status is complete.
    where am i going wrong, how do i make this work?
    THANKS IN ADVANCE
    Abhinav

    Hi,
    Why do you want to do
    SELECT  *
    FROM    table_name;
    inside the procedure?  Why not have your script run the procedure (without the query above), and then do that query afterwards, when you can use SPOOL to put the results in a file?
    If you really must write a file from a procedure, here's an example of how to use utl_file.
    First, SYSTEM (or some other user with the CREATE ANY DIRECCTORY system privilege) must create a directory, and grant privileges to use it.  For example:
    CREATE OR RPLEACE DIRECTORY  a_dir  AS 'C:\Foo\A_Folder';
    GRANT ALL ON DIRECTORY  a_dir  TO PUBLIC;
    Typically, SYSTEM does this once, and other people use it hundreds of times.
    You might create a file in that directory like this:
    CREATE OR REPLACE PROCEDURE  write_dept
    IS
        f  utl_file.file_type;
    BEGIN
        f := utl_file.fopen ('A_DIR', 'Dept.txt', 'W');
        FOR  r  IN  (  SELECT  *
                       FROM    scott.dept
        LOOP
            utl_file.put_line ( f
                              , TO_CHAR (r.deptno, 'FM00')
                                || ' '
                                || RPAD (r.dname, 15)
                                || r.loc
        END LOOP;
        utl_file.fclose (f);
    END  write_dept;
    SHOW ERRORS

  • Can we use return statement in procedure?

    Can we use return statement in procedure or we can use more than one return statement in procedure?

    HamidHelal wrote:
    NOReally? Did you at least test it? You can use RETURN in procedure or in anonymous PL/SQL block. The only restriction is you can't specify return value:
    SQL> begin
      2      dbms_output.put_line('Before return');
      3      return;
      4      dbms_output.put_line('After return');
      5  end;
      6  /
    Before return
    PL/SQL procedure successfully completed.
    SQL> create or replace
      2    procedure p1
      3      is
      4      begin
      5          dbms_output.put_line('Before return');
      6          return;
      7          dbms_output.put_line('After return');
      8  end;
      9  /
    Procedure created.
    SQL> exec p1;
    Before return
    PL/SQL procedure successfully completed.
    SQL> begin
      2      dbms_output.put_line('Before return');
      3      return 99;
      4          dbms_output.put_line('After return');
      5  end;
      6  /
        return 99;
    ERROR at line 3:
    ORA-06550: line 3, column 5:
    PLS-00372: In a procedure, RETURN statement cannot contain an expression
    ORA-06550: line 3, column 5:
    PL/SQL: Statement ignored
    SQL> create or replace
      2    procedure p1
      3      is
      4      begin
      5          dbms_output.put_line('Before return');
      6          return 99;
      7          dbms_output.put_line('After return');
      8  end;
      9  /
    Warning: Procedure created with compilation errors.
    SQL> show err
    Errors for PROCEDURE P1:
    LINE/COL ERROR
    5/9      PL/SQL: Statement ignored
    5/9      PLS-00372: In a procedure, RETURN statement cannot contain an
             expression
    SQL> SY.

  • Email multiple spools from background job - SM36 using Spool List recipient

    I create a background job using Spool List Recipient to email me the reports. The program that I scheduled to run creates 2 spools. When the spools are sent via email, only the last spool is sent.
    Please advise on how I can get the 2 spools sent via email.

    i would not use the Spool List recipient from Job and use the function RSPO_SPOOLJOB_TO_OFFICE in your Program instead.
    tell me if it helps.
    Regards,
    Laurent

  • Preserve a single space at the end of line using spool command

    Hi,
    Can you please help me to write the result of an sql query into a file with the last column of the row ending with a single space?
    For example:
    COL1DATA|COL2DATA|COL3DATA<space1>
    As mentioned in the example the col3 value in the file should end with a single space. And there should not be any delimiters at the end of the row.
    I tried with set trimspool on/off. But, it didn't work. When I say trimspool on - it is trimming all the trailing spaces.
    When I say trimspool off - it is retaining all the trailing spaces to the size of the line.
    But, I do not wish to modify the file through shell commands once it is written thru spool. I mean I do not wish to append spaces to the end of a line using shell script or any other method.
    I do not wish to use other methods like UTL_FILE also.
    Please help me how to do it using spool command?
    Thank you.
    Ramana

    My requirement is that all the trailing spaces should be truncated except the last one in the row.Why?
    As you have discovered a single column in sqlplus, is always a fixed length regardless of the size of the data, if the length of the data varies the output is padded to the maximum or line size with spaces. The trim and trimpsool commands are there to remove all the spaces from the end of a line if there are any. There are no commands to trim all the spaces except one, or even to trim all the spaces except two, or three even.
    If you want such custom processing you should post process the file in the OS using sed, awk or perl or something designed for such things.

  • Tax calculation in CRM using R/3 pricing procedure

    Hello Experts
    We are using R/3 pricing procedure to calculate list prices in CRM.
    The condition record for Taxes are maintained for condition type UTXJ in SD which is calling for tax procedure TAXUSJ and condition type JR1. 
    The records are maintained in FTXP.  This is the SAP Standard way of maintaining taxes if external tax software is not used.
    We have downloaded the condition records and condition types in CRM.  The tables have all the required records downloaded from R/3.
    When creating an order in Webshop the tax is not getting calculated.
    The pricing analysis shows that the condition record for UTXJ condtion type is met, but it is not showing the tax maintained for condition type JR1. 
    Have we missed any settings here? 
    If we are using R/3 billling does the TTE needs to be activated for calculating taxes in the webshop?
    If TTE needed to be used for calculating taxes, what are the settings needed to be configured?
    Thanks in advance for the valuable advice.
    Sastri

    Hi Sastri,
    I am facing this problem with TAX Condition Records: Pricing error: Mandatory condition MWST is missing. I am using a R/3 pricing procedure correctly downloaded to CRM.
    You say that you have downloaded the condition records and condition types in CRM. SAP Library says 'Prerrequisites: You have downloaded the tax condition records from SAP ECC'.
    I don't know If my problem is caused because I haven't downloaded any Tax Condition Records. The fact is that I cannot determine which one is the Condition Object to download in R3AS.
    I would really appreciate if you or anyone could tell me which object you did use.
    thanks in advance,
    Pablo
    Edited by: Pablo Rodríguez Mateos on Sep 30, 2009 12:30 PM
    Edited by: Pablo Rodríguez Mateos on Sep 30, 2009 8:59 PM
    Solved!

  • Using dynamic value in procedure on column

    I want a PL/sql procedure to select the data from the column dynamically into a variable .
    My friend suggested its not possible in PL/sql ,its only possible in sql .
    What i want is when i execute the PL/sql procedure the a_1 must get the value of the data in the table,i do not want to use execute immediate in pl/sql.
    I create a table A
    create table A (a1 number,a2 number,a3 number);
    insert into a values (1,2,3);
    then i create a procedure
    create or replace
    procedure test_a (var IN number)
    as
    a_1 number;
    i number;
    z varchar2(5);
    begin
    if var=1
    then
    i:=1;
    elsif var = 2
    then
    i:=2;
    z:='A2';
    end if;
    SELECT 'a'||i into a_1 from a;
    end;
    Edited by: user536416 on May 13, 2010 4:03 AM

    I prefer reference cursors over execute immediate if I must do dynamic SQL (and have learned not to do it unless necessary - among other things dynamic SQL is hard to debug and maintain).
    The advantages to ref cursors are
    * execute immedate will only retrieve one row, ref cursors as many as you want
    * easier for me to build the query first, then execute it (though you can do this with execute immediate too) for debugging
    You can buiid the query dynamcially but have to be careful to make sure the select list matches the INTO clause on the fetch statements. Although the queries in the example below are hard coded I could have done something like
      v_command_c := 'select '||var1||', '||var2||' from '''||table_name||'''';
      open refcur for v_command_c;To randomize your column selection use something like the above with IF logic and a randomizer, possibly the DBMS_RANDOM package or a time extraction.
    Something like
    SET SCAN OFF
    SET SERVEROUTPUT ON
    DECLARE
      --define composite data types
      --reference cursor type - structure
      TYPE RefCursorType   IS REF CURSOR;
      --collection (index-by table) type - structure
      TYPE TablesTableType IS TABLE OF user_tables.table_name%TYPE
        INDEX BY BINARY_INTEGER;
      --define ref cursors to be used in BEGIN section
      UserTablesCursor RefCursorType;
      UserViewCursor   RefCursorType;
      --define actual index-by tables to be used in BEGIN section
      NamesTable TablesTableType;
      ViewsTable TablesTableType;
      --define internal procedures to be used in this script
      PROCEDURE ListItems(RefCursor IN RefCursorType,
        DataTable IN OUT TablesTableType
        ) IS
        Counter   INTEGER := 1;
        TableName user_tables.table_name%TYPE;
      BEGIN
        FETCH RefCursor INTO DataTable(Counter);
        Counter := Counter + 1;
        WHILE RefCursor%FOUND LOOP
          FETCH RefCursor INTO DataTable(Counter);
          Counter := Counter + 1;
        END LOOP;
      END; --ListItems;
      PROCEDURE WriteItems(DataTable IN TablesTableType) IS
      BEGIN
        FOR i IN 1..DataTable.count LOOP
          dbms_output.put_line(DataTable(i));
        END LOOP;
      END; --WriteItems;
    BEGIN
      OPEN UserTablesCursor FOR
        SELECT table_name
          FROM user_tables;
      ListItems(UserTablesCursor,NamesTable);
      CLOSE UserTablesCursor;
      dbms_output.put_line('user_tables');
      dbms_output.put_line('--------------');
      WriteItems(NamesTable);
      --second defintion & set of calls
      dbms_output.put_Line(CHR(13));
      OPEN UserTablesCursor FOR
        SELECT view_name
          FROM user_views;
      ListItems(UserTablesCursor,ViewsTable);
      CLOSE UserTablesCursor;
      dbms_output.put_line('user_views');
      dbms_output.put_line('--------------');
      WriteItems(ViewsTable);
    END;
    /Edited by: riedelme on May 13, 2010 5:44 AM

  • Subreport using the same Stored Procedure

    I have a main report and a subreport that uses the same stored procedure. The stored procedure has 12 parameters and what I want to avoid is the user having to enter the same parameter values twice. When I created the subreport I put in the parameters + one field, the employee id field so that I could just test it on one employee.
    After I entered the subreport into the main report, when I got to refresh the data, it's asking for params for BOTH reports. Is there any way to get around this? Because of the way the stored procedure returns the data, I had to create a subreport instead of just fitting it into one of the footers. I've looked at the subreport link and added the employee id as the key. When I ran it the first time, it returned the wrong date range on the sub.
    Help! this thing is Way passed due!!

    Right click on the sub report and choose change sub report links
    Top left pane contains your main report parameters use > to add
    In the bottom left corner of that dialog then scroll down until you see the corresponding sub report parameter
    Repeat for each parameter
    This should then take the main report params and pass into the sub report

  • Use of variable in Procedure

    I created a global variable that contains a result of a query.
    I used it in a procedure using SQL but when I run the prcedure I have the following error :
    com.sunopsis.sql.SnpsMissingParametersException: Missing parameter
    Could you tell me how to use my variable ?
    My SQL Code is the following and I bolded the variable
    SELECT A.SESS_NAME ,
    A.SCEN_VERSION,
    A.SESS_BEG ,
    A.SESS_DUR,
    C.NNO,
    RTRIM(LTRIM(B.STEP_NAME)) TABLE_NAME
    ,SUM(C.STEP_DUR)
    , SUM(NB_INS) NB_INS
    FROM COUNT_TMP D , SNP_SESSION A , SNP_SESS_STEP B, snp_step_log C
    WHERE
    'PS_' || RTRIM(LTRIM(B.STEP_NAME)) = D.TABLE_NAME AND
    A.SESS_BEG >= TO_DATE( #DATE_BASCULE , 'DD/MM/YYYY') AND
    A.SESS_NO = B.SESS_NO AND
    B.SESS_NO = C.SESS_NO AND B.NNO = C.NNO
    GROUP BY A.SESS_NAME , A.SCEN_VERSION ,A.SESS_BEG ,A.SESS_DUR, C.NNO ,B.STEP_NAME
    ORDER BY A.SESS_NAME , A.SCEN_VERSION, C.NNO
    Thank you
    Meapri

    Thanks a lot it did not fail.
    Now I am going to check if my procedure does something.
    Steps to use a variable resulting from a query in a procedure. ( In my case I used a alphanumeric variable )
    1) I declare a global Variable My_Variable. I chose
    - type 'Alphanumeric'
    - default value SELECT TO_CHAR(DATE_LAST_PROCESS) FROM PS_S1_ODI_BASCULE
    - action 'Dernière valeur'
    - I refresh my variable by running the query on the RDBMS
    2)In the procedure I refer to my variable by writing '#My_Variable'. My SQL Code becomes
    SELECT A.SESS_NAME ,
    A.SCEN_VERSION,
    A.SESS_BEG ,
    A.SESS_DUR,
    C.NNO,
    RTRIM(LTRIM(B.STEP_NAME)) TABLE_NAME
    ,SUM(C.STEP_DUR)
    , SUM(NB_INS) NB_INS
    FROM COUNT_TMP D , SNP_SESSION A , SNP_SESS_STEP B, snp_step_log C
    WHERE
    'PS_' || RTRIM(LTRIM(B.STEP_NAME)) = D.TABLE_NAME AND
    A.SESS_BEG >= TO_DATE( '#DATE_BASCULE' , 'DD/MM/YYYY') AND
    A.SESS_NO = B.SESS_NO AND
    B.SESS_NO = C.SESS_NO AND B.NNO = C.NNO
    GROUP BY A.SESS_NAME , A.SCEN_VERSION ,A.SESS_BEG ,A.SESS_DUR, C.NNO ,B.STEP_NAME
    ORDER BY A.SESS_NAME , A.SCEN_VERSION, C.NNO

  • How to Know one condition Type (PR00) used in which pricing procedures

    Hi Friends,
    I have 20 pricing procdures I need information that condition type PR00 is used in which pricing procedures.
    by help of
      any report
      any table etc
    Thanking you
    Arun

    Dear Customer,
    in standard there is no report available for your requirement.
    In this case you can only create your own selection report therefore.
    regards
    Claudia

  • How to find the columns and tables used in a stored procedure?

    Hi,
    Can someone suggest how to find the columns and tables used within a stored procedure?
    Thanks
    VBK

    For example:
    SQL> create or replace
      2    procedure p1
      3      is
      4          cnt number;
      5      begin
      6          select count(*) into cnt from emp;
      7  end;
      8  /
    Procedure created.
    SQL> select  referenced_owner,
      2          referenced_name
      3    from  dba_dependencies
      4    where owner = 'SCOTT'
      5      and name = 'P1'
      6      and referenced_type = 'TABLE'
      7  /
    REFERENCED_OWNER               REFERENCED_NAME
    SCOTT                          EMP
    SQL> SY.

  • Use of function and procedures

    when we need to use function rather than procedure or viceversa???

    Welcome to the forum!
    Use a function if you want to use the value it returns as you would use any other expression in a SQL statement:
    SELECT  SYSDATE
    ,       my_function (column1)  AS c1
    ,       UPPER (column2)        AS c2
    FROM    table_x;or in PL/SQL:
    IF  my_function (x) > 0  THEN  ...Use a procedure otherwise; for example, if there is no value to be passed back.
    Functions can have OUT (and IN OUT) arguments, but they can cause confusion. Many people use procedures whenever they need OUT arguemnts, which includes all situations where 2 or more values are passed back.
    Any good book or site on PL/SQL, or any kind of procedural programming, should explain the differences between functions and procedures.
    If you don't have at least that much guidance, it's better not to try using PL/SQL.

  • Find all tables used in a stored procedure

    Hi,
    I have a requirement where i have to find all the tables used in a stored procedures from different  databases.
    Ex: i have a stored procedure where i use few tables from MASTER database and some from STAGE database.When i have written a query to find all tables used in the stored procedure, i am getting only those database table where i run the query and procedure
    exists.
    I have stored procedure SP1 in Master database, but i use the tables from both master and stage.
    When i run this, i am getting the tables only from Master database but not from stage. i hope my requirement is clear.
    I am trying to find all the tables from all databases used by a stored proc.
    ;WITH stored_procedures AS (
    SELECT 
    o.name AS proc_name, oo.name AS table_name,
    ROW_NUMBER() OVER(partition by o.name,oo.name ORDER BY o.name,oo.name) AS row
    FROM sysdepends d 
    INNER JOIN sysobjects o ON o.id=d.id
    INNER JOIN sysobjects oo ON oo.id=d.depid
    WHERE o.xtype = 'P')
    SELECT proc_name, table_name FROM stored_procedures
    WHERE row = 1
    ORDER BY proc_name
    Please advice

    Your question is not entirely clear. You need to run the query on different databases.
    You may find this blog post helpful
    How to get information about all databases without a loop
    Check the last script in that blog post and modify to your particular purpose.
    For every expert, there is an equal and opposite expert. - Becker's Law
    My blog
    My TechNet articles

  • Database updation using XML and stored Procedure?

    Hello,
    I want to perform updation in multiple tables using XML files.Please suggest can I do updation using xml and stored procedure.
    If yes then which is more efficient and takes less time.
    1.Updation using xml files only
    2.Updation using xml files with stored procedure.
    3.Stored procedure alone.
    If direct xml and stored procedure communication is possible.then please write how.
    Thanks in advance for any help.

    Here's a sample. The next code drop of the XSQL Servlet will make the easy-to-do from within XSQL Pages:
    package package1;
    import org.w3c.dom.*;
    import java.sql.*;
    import oracle.jdbc.driver.*;
    import oracle.xml.sql.query.OracleXMLQuery;
    public class Class1 extends Object {
    public static void main( String[] arg ) throws Exception {
    Connection conn = getConnection();
    CallableStatement ocs = conn.prepareCall("begin ? := App.HotItems('PAUL'); end;");
    ocs.registerOutParameter(1,OracleTypes.CURSOR);
    ocs.execute();
    ResultSet rs = ((OracleCallableStatement)ocs).getCursor(1);
    OracleXMLQuery oxq = new OracleXMLQuery(conn,rs);
    System.out.println(oxq.getXMLString());
    oxq.close();
    rs.close();
    ocs.close();
    conn.close();
    public static Connection getConnection() throws Exception {
    String username = "scott";
    String password = "tiger";
    String dburl = "jdbc:oracle:thin:@localhost:1521:xml";
    String driverClass = "oracle.jdbc.driver.OracleDriver";
    Driver d = (Driver)Class.forName(driverClass).newInstance();
    return DriverManager.getConnection(dburl,username,password);
    null

  • Fibonacci series using recusrion in a Procedure

    Hi,
    Could anyone please help me to query a fibonacci series using recusrion in a Procedure.

    Create or replace Function fnu_fibonnaci(p_iNumber integer)
    return integer
    is
      nuFib  integer;
      nuP  integer;
      nuQ  integer;
    Begin
      if p_iNumber is not null then
         if p_iNumber=0 then
            nuFib:=0;
         Elsif p_iNumber=1 then
                nuFib:=1;
         Else
            nuP:=0;
            nuQ:=1;
            For nuI in 2..p_iNumber loop
                nuFib:=nuP+nuQ;
                nuP:=nuQ;
                nuQ:=nuFib;
            End loop;
         End if;
      End if;
      return(nuFib);
    End fnu_fibonnaci;from
    http://rosettacode.org/wiki/Fibonacci_sequence#PL.2FSQL

Maybe you are looking for

  • Adobe pdf converter question

    I am trying to print a document from a DOS window to the "Adobe PDF" printer that converts documents printed to PDF files. It is using the standard DOS print job called "Remote downlevel document". It shows this job in the print queue for a moment bu

  • Pixels and document size differences in Illustrator compared to Photoshop

    Why is the pixel ratio of a project in illustrator different than that of the same pixel ratio of a project in Photoshop?  Example:  A project can in Illustrator can have an artboard of 950px X 950px and be 12in and in Photoshop that same pixel ratio

  • How do i remove extra tool bars that i've added?

    I've added two tool bars, and one of them changed the google search engine to a yahoo, and it just wastes space. I'd like to remove both of them but i can't find on the website how. I just need to know if there's somewhere i can click and it just goe

  • Deactivating Adobe Standard 8 from dead machine and Download licensed version

    My work laptop died.  I had Adobe writer 8 standard (same as Adobe standard 8?) on it.  I have the license key.  How do I get it installed on my new machine?  do I need to dactivate from my dead laptop?  how do i do that?  Also, I can't find a link t

  • 13" Macbook colour display issue HELP

    Hi, I hope someone can help with this, my cat has stood on the keyboard of my laptop and changed the colour scheme on my screen, Blue has gone orange and they other colours have completely changed have tried to change it back through the display but