Exiting from SQL script

Hi,
How do you exit from an sql script?
e.g
DECLARE
VAR1 = VARCHAR2(10);
VAR2 = VARCHAR2(10);
BEGIN
VAR1 := 'hello';
VAR2 := 'world';
IF VAR1 != VAR2
THEN
DBMS_OUTPUT.PUT_LINE('Variables not equal');
## Exit here! <------- HOW?????
END IF;
END;
Cheers,
Warren

If I understand correctly, you have a series of anonymous PL/SQL blocks in a script. If some test fails in one of them, then you do not want to run the rest of the script.
If exiting sqlplus is an acceptable means of failing, then you can do something like:
WHENEVER SQLERROR EXIT 1;
DECLARE
v1 VARCHAR2(20);
v2 VARCHAR2(20);
BEGIN
   v1 := 'ABCDE';
   v2 := 'FBCDE';
   IF v1 <> v2 THEN
      DBMS_OUTPUT.Put_Line('Variables Not Equal');
      RAISE NO_DATA_FOUND;
   END IF;
END;
DECLARE
v3 VARCHAR2(20);
BEGIN
   v3 := 'Second Block';
END;
/in your script. As shown, the script will exit sqlplus without executing the second block. You can use any sql error instead of no data found.
Another possibility if exiting sqlplus is not acceptable would be to do something like this in your script:
VARIABLE failed NUMBER;
DECLARE
v1 VARCHAR2(20);
v2 VARCHAR2(20);
BEGIN
   :failed := 0;
   v1 := 'ABCDE';
   v2 := 'FBCDE';
   IF v1 <> v2 THEN
      DBMS_OUTPUT.Put_Line('Variables Not Equal');
      :failed := 1;
      RETURN;
   END IF;
END;
DECLARE
v3 VARCHAR2(20);
BEGIN
   IF :failed = 0 THEN
      v3 := 'Second Block';
   END IF;
END;
/Note, the IF :failed = 0/END IF block should cover all the code in each subsequent anonymous block.
A third approach would be to re-write the series of anonymous blocks as a package, then create a small driver script to call each procedure in turn unless one returns an error.
TTFN
John

Similar Messages

  • Conditional Exit from the script

    Hi,
    I have to code the script like the below
    --Step 1
    begin
    If <Table1 doesnot exist> then
    Display "User Defined Error Message: Table1 doesnot exit"
    EXIT FROM THE SCRIPT(Below sql should not run)
    endif
    end
    --Step 2
    spool abc.txt;
    select "should not run" from Table1;
    spool off;Step 2 should not run if table1 doesnot exist.
    Can someone please tell how to conditionally exit the script.
    Thanks & Regards,C
    CDPrasad
    Edited by: cdprasad on Aug 12, 2010 1:35 PM
    Edited by: cdprasad on Aug 12, 2010 1:36 PM
    Edited by: cdprasad on Aug 12, 2010 1:38 PM
    Edited by: cdprasad on Aug 12, 2010 1:38 PM

    Hi,
    David is right; SQL*Plus is the wrong tool for this job.
    If you really want to to this in SQL*Plus, you can achieve a crude type of branching by using sub-sripts. Instead of an IF statement, you use START or @ to run one or another of those sub-scripts, based on a substitution variable, which in turn is set by a query.
    For example:
    --     abc.sql - Test if table1 exists, and
    --                     (1) if it exists, run abc_query.sql to do a query
    --                     (2) if it does not exist, run abc_error.sql to display an error message
    --     Preliminary query, to define next_script:
    COLUMN     next_script_col        NEW_VALUE next_script
    SELECT     CASE      COUNT (*)
             WHEN  0  THEN  'abc_error'
                       ELSE  'abc_query'
         END     AS next_script_col
    FROM     all_tables
    WHERE     table_name     = 'TABLE1'
    AND     owner          = 'SCOTT'
    --     Now that we know what to do, do it:
    @&next_scriptYou would run the above script (abc.sql) and it would decide whether to run the script containing you query, or the script that prints an error message.
    Why does table1 sometimes disappear? In a good database design, tables are permanent structures, and get dropped only when they are obsolete. Perhaps you should be TRUNCATing the table, not dropping it.

  • How to exit from SQL PlUS

    HI,I came to know that direct exit from SQL Plus without Oracle shutdown causes future issues of ORA-0600 kind of errors. Is it true? If yes could u pls suggest me how to shutdown from user "SYSTEM/manager". Bcoz with this am warned that I dont have previleges.

    Hello,
    HI,I came to know that direct exit from SQL Plus without Oracle shutdown causes future issues of ORA-0600 kind of errors. Is it true?The ORA-00600 is an internal error it can be caused for instance by a Bug, a corruption, ... , and if someday you experience this kind of error, you should open a Service Request to My Oracle Support.
    However, I've never heard that exiting sqlplus could cause this kind of error. Where did you get such information ?
    how to shutdown from user "SYSTEM/manager". To shutdown the database you should be connected with the User SYS (as SYSDBA). You may use the following statement:
    sqlplus /nolog
    connect / as sysdba
    shutdown immediate;
    exitHope this help.
    Best regards,
    Jean-Valentin

  • How to exit from SQL*Plus based on the return value of a SQL select stment?

    Hi
    I have a SQL script executed from SQL*Plus. I would like to know if SQL*Plus
    supports any kind of branching or exiting from script execution based on a
    returned value of a SQL select statement. I am on 9i.
    Regards,
    Tamas Szecsy

    in sqlplus, you have whenever
    ex:
    whenever sqlerror exit failure
    insert into ...
    -- if this fails, then you will be out
    insert into ...
    -- if this fails, then you will be out
    whenever sqlerror continue
    insert into ...
    -- if this fails, this continues
    insert into ...and you have PL/SQL
    declare x number;
    begin
    select count(*) into x from emp;
    if (x=14) then null; end if;
    end;
    /note that you can mix those in some case
    -- exit if there is no row in emp
    whenever sqlerror exit 1
    var dummy number
    exec select count(*) into :dummy from emp having count(*)!=0

  • I need to get error from sql script launched from class

    Hello.
    I need to run a bat file (windows xp) inside a PL/SQL procedure and I must check the codes returned by the command.
    I am trying with these files:
    comando.bat
    sqlplus -s fernando/sayaka@ferbd %1
    exit /Bkk.sql
    whenever sqlerror exit sql.sqlcode rollback
    declare
      v_res number;
    begin
      select 1
           into v_res
           from dual
       where 1=2;
    end;
    exit sql.sqlcodeEjecutarProcesoSOreturn.java
    import java.lang.Runtime; 
    import java.lang.Process; 
    import java.io.IOException; 
    import java.lang.InterruptedException;   
    public class EjecutarProcesoSOreturn
        public static int ejecuta(java.lang.String  arg0, java.lang.String arg1)
            java.lang.String[] args= new String[2];
            args[0]=arg0;
            args[1]=arg1;
            int ret = 0;
            System.out.println("En ejecuta");           
            try
                /* Se ejecta el comando utilizando el objeto Runtime
                y Process */               
                Process p = Runtime.getRuntime().exec(args);      
                try
                    /* Esperamos la finalizacion del proceso */                 
                    ret = p.waitFor(); 
                    //ret = p.exitValue();                
                catch (InterruptedException intexc)
                    System.out.println("Se ha interrumpido el waitFor: " +  intexc.getMessage());
                    ret = -1;            
                System.out.println("Codigo de retorno: "+ ret);    
            catch (IOException e)
               System.out.println("IO Exception de exec : " +               e.getMessage());              
               e.printStackTrace();          
               ret = -1;            
            finally
               return ret;
        public static void main(java.lang.String[] args)
            System.out.println("En main");  
            System.out.println("args[0] " + args[0]);           
            System.out.println("args[1] " + args[1]);   
            ejecuta(args[0], args[1]);
    }  When I launch the script from a console I get:
    D:\Ejercicios_Oracle\BATCH_SCRIPTS>comando.bat @kk.sql
    D:\Ejercicios_Oracle\BATCH_SCRIPTS>sqlplus -s fernando/sayaka@ferbd @kk.sql
    declare
    ERROR en lÝnea 1:
    ORA-01403: no se han encontrado datos
    ORA-06512: en lÝnea 4
    D:\Ejercicios_Oracle\BATCH_SCRIPTS>exit /BAnd if I check the errorlevel I get:
    D:\Ejercicios_Oracle\BATCH_SCRIPTS>echo %errorlevel%
    1403When I run it the class I get:
    D:\Ejercicios_Oracle\BATCH_SCRIPTS>java EjecutarProcesoSOreturn comando.bat @kk.sql
    En main
    args[0] comando.bat
    args[1] @kk.sql
    En ejecuta
    Codigo de retorno: 0And if I check the errorlevel I get:
    D:\Ejercicios_Oracle\BATCH_SCRIPTS>echo %errorlevel%
    0How can I get the code 1403 returned from the class?
    Thanks in advance.

    I am trying to extract the error code from the Process.getInputStream() but it seems as if I do not have some privileges.
    This is my class right now:
    import java.lang.Runtime; 
    import java.lang.Process; 
    import java.io.IOException; 
    import java.lang.InterruptedException;   
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.io.InputStream;
    public class EjecutarProcesoSOreturn
        public static int ejecuta(java.lang.String  arg0, java.lang.String arg1)
            java.lang.String[] args= new String[2];
            args[0]=arg0;
            args[1]=arg1;
    int ret = -100;
            //System.out.println("En ejecuta");           
            try
                /* Se ejecuta el comando utilizando el objeto Runtime y Process */     
                Process p = Runtime.getRuntime().exec(args);      
    ret = -101;   
                try
                    /* Esperamos la finalizacion del proceso */                 
                    ret = p.waitFor(); 
                    //ret = p.exitValue();
                    InputStream bis = p.getInputStream();
                    InputStreamReader isr = new InputStreamReader(bis);
                    BufferedReader br = new BufferedReader(isr);
                    String line = null;
                    String msg = null;
                    String errCode = null;
                    boolean oraError = false;
    ret = -102;   
                    while ( (line = br.readLine()) != null)   
                      //System.out.println(line);
                      if ((line.length() >= 5) & (!oraError))
                        msg = line.substring(0,4); 
                        if (msg.equals("ORA-"))
                             oraError = true;
                             errCode = line.substring(4,9);
    ret = -103;   
                          //System.out.println(errCode);
                          ret = Integer.parseInt(errCode);;
                catch (InterruptedException intexc)
                    //System.out.println("Se ha interrumpido el waitFor: " +  intexc.getMessage());
                    ret = -1;            
            catch (IOException e)
               //System.out.println("IO Exception de exec : " +               e.getMessage());              
               //e.printStackTrace();          
               ret = -1;            
            catch (Exception e)
               //System.out.println("IO Exception de exec : " +               e.getMessage());              
               //e.printStackTrace();          
               ret = -104;            
            finally
               //ret = -100;   
               System.out.println("Codigo de retorno: "+ ret);
               return ret;
        public static void main(java.lang.String[] args)
            System.out.println("En main");  
            System.out.println("args[0] " + args[0]);           
            System.out.println("args[1] " + args[1]);   
            ejecuta(args[0], args[1]);
    }  And when I call the main method with these parameters then I get:
    D:\Ejercicios_Oracle\BATCH_SCRIPTS>java EjecutarProcesoSOreturn d:\comando.bat @d:\kk.sql
    En main
    args[0] d:\comando.bat
    args[1] @d:\kk.sql
    Codigo de retorno: 1403I have this pl/sql function:
    CREATE OR REPLACE FUNCTION FERNANDO.EjecutarProcesoSOreturn (param1 VARCHAR2, param2 VARCHAR2) return NUMBER
    AS LANGUAGE JAVA  name 'EjecutarProcesoSOreturn.ejecuta(java.lang.String, java.lang.String) return java.lang.int';I have granted some privileges to the user FERNANDO:
    begin
        dbms_java.grant_permission
        ('FERNANDO',
         'java.io.FilePermission',
         'd:\comando.bat',
         'execute');
        dbms_java.grant_permission
        ('FERNANDO',
         'java.lang.RuntimePermission',
         'writeFileDescriptor' );
        dbms_java.grant_permission
        ('FERNANDO',
         'java.lang.RuntimePermission',
         'readFileDescriptor' );
        dbms_java.grant_permission
        ('FERNANDO',                   
         'java.io.FilePermission',    
         'd:\*',               
         'read,write');
    end;
    /and when I try the function, I get:
    SQL> DECLARE
      2    RetVal NUMBER := 0;
      3    PARAM1 VARCHAR2(200);
      4    PARAM2 VARCHAR2(200);
      5 
      6  BEGIN
      7    PARAM1 := 'd:\comando.bat';
      8    PARAM2 := '@d:\kk.sql';
      9 
    10    RetVal := EJECUTARPROCESOSORETURN ( PARAM1, PARAM2 );
    11    dbms_output.put_line('RetVal: '||RetVal);
    12    --ROLLBACK;
    13  END;
    14  /
    RetVal: -102Could you please tell me what my problem is?

  • How to accept user inputs from  sql script

    I want to create Tablespace useing sql script , but the location of the data file I need accept from user . (to get the location of the data file ) .
    How can I accept user input from pl/sql .
    Example :
      CREATE TABLESPACE  TSPACE_INDIA LOGGING
         DATAFILE 'H:\ORACLE_DATA\FRSDB\TSPACE_INDI_D1_01.dbf'
         SIZE 500M  AUTOEXTEND ON NEXT  1280K MAXSIZE UNLIMITED
         EXTENT MANAGEMENT LOCAL;here I need to accept location of the datafile from user ie : 'H:\ORACLE_DATA\FRSDB\TSPACE_INDI_D1_01.dbf'

    Hi,
    Whenenever you write dynamic SQL, put the SQL text into a variable. During development, display the variable instead of executing it. If it looks okay, then you can try executing it in addition to displaying it. When you're finished testing, then you can comment out or delete the display.
    For example:
    SET     SERVEROUTPUT     ON
    DECLARE
        flocation     VARCHAR2 (300);
        sql_txt     VARCHAR2 (1000);
    BEGIN
        SELECT  '&Enter_The_Path'
        INTO    flocation
        FROM    dual;
        sql_txt :=  'CREATE TABLESPACE SRC_TSPACE_INDIA LOGGING
         DATAFILE' || flocation || ' "\SRC_TSPACE_INDI_D1_01.dbf" ' || '
         SIZE 500M  AUTOEXTEND ON NEXT  1280K MAXSIZE UNLIMITED
         EXTENT MANAGEMENT LOCAL ';
        dbms_output.put_line (sql_txt || ' = sql_txt');
    --  EXECUTE IMMEDIATE sql_txt;
    END;
    /When you run it, you'll see something like this:
    Enter value for enter_the_path: c:\d\fubar
    old   5:     SELECT  '&Enter_The_Path'
    new   5:     SELECT  'c:\d\fubar'
    CREATE TABLESPACE SRC_TSPACE_INDIA LOGGING
         DATAFILEc:\d\fubar
    "\SRC_TSPACE_INDI_D1_01.dbf"
         SIZE 500M  AUTOEXTEND ON NEXT  1280K MAXSIZE
    UNLIMITED
         EXTENT MANAGEMENT LOCAL  = sql_txt
    PL/SQL procedure successfully completed.This makes it easy to see that you're missing a space after the keyword DATAFILE. There are other errrors, too. For example, the path name has to be inside the quotes with the file name, without a line-feed between them, and the quotes should be single-quotes, not double-quotes.
    Is there some reason why you're using PL/SQL? In SQL, you can just say:
    CREATE TABLESPACE SRC_TSPACE_INDIA LOGGING
    DATAFILE  '&Enter_The_Path\SRC_TSPACE_INDI_D1_01.dbf'
    SIZE 500M  AUTOEXTEND ON NEXT  1280K MAXSIZE UNLIMITED
    EXTENT MANAGEMENT LOCAL;though I would use an ACCEPT command to given a better prompt.
    Given that you want to use PL/SQL, you could assign the value above to sql_txt. If you need a separate PL/SQL variable for flocation, then you can assign it without using dual, for example:
    DECLARE
        flocation     VARCHAR2 (300)     := '&Enter_The_Path';The dual table isn't needed very much in PL/SQL.
    Edited by: Frank Kulash on Jan 10, 2013 6:56 AM

  • Question about correctly EXIT on SQL Script

    Hi there,
    I have created a SQL script, every time when the raise_application error appears then of course the PL/SQL block ends but then still the external sql script is being executed, how can I prevent the External sql script from being executed after a raise application error is displayed?
    Regards
    RobH
    DECLARE
    BEGIN
    IF start_date > stop_date
    THEN
    raise_application_error (-020110,
    'Start Date can not be greater Stop Date. '
    ELSE ..... do some selecting and inserting of data into temporary tables etc...
    END IF;
    END;
    --And now a external SQL script should be started...
    @c:\reports\test.sql

    you can trap your exception in the inner block using EXCEPTION block and from there propagate it to the external block to stop further processing. something like this...
    DECLARE
      l_deptno NUMBER;
    BEGIN
      FOR i IN (SELECT deptno FROM dept)
      LOOP
        BEGIN
          FOR j IN (SELECT empno, ename FROM emp WHERE deptno = i.deptno)
          LOOP
            IF ( i.deptno = 20 ) THEN
              RAISE_APPLICATION_ERROR(-20001, 'Error Raised');
            ELSE
              DBMS_OUTPUT.PUT_LINE('Dept = ' || i.deptno || ' EmpNo: ' || j.empno || ' EName: ' || j.ename);
            END IF;
          END LOOP;
        EXCEPTION
          WHEN OTHERS THEN
            DBMS_OUTPUT.PUT_LINE('Error Trapped Inside');
            RAISE;
        END;
      END LOOP;
    EXCEPTION
      WHEN OTHERS THEN
        DBMS_OUTPUT.PUT_LINE('Error Trapped Outside');
    END;
    SQL> /
    Dept = 10 EmpNo: 7782 EName: CLARK
    Dept = 10 EmpNo: 7839 EName: KING
    Dept = 10 EmpNo: 7934 EName: MILLER
    Error Trapped Inside
    Error Trapped Outside
    PL/SQL procedure successfully completed.

  • Update data from SQL Script

    If my data is the following...
    Table: PRODUCT
    Field."Item": B03934 SSAPRDIM
    SA position 11,12
    PR position 13,14
    DI position 15,15
    I need to break the item number into three and post these three different values into another fields called STONE1, STONE2, STONE3, but i need to do validation with STONE CODE to make sure SA, PR, and DI are the valid value before posting (UPDATE SQL)
    how to do it???
    UPDATE PRODUCT
    SET STONE1
    (SELECT substr(item,11,2) p
    from product, stone_code
    where substr(item,11,2) = stone_code.code)
    i am not sure if this is the way to go.

    Maybe
    update product
       set stone1 = 'SA',
           stone2 = 'PR',
           stone3 = 'DI'
    where substr(item,11,6) = 'SAPRDI'or individual treatment of stone ...
    update product p
       set (stone1,stone2,stone3) = (select case when substr(item,11,2) = 'SA' then 'SA' end,
                                            case when substr(item,13,2) = 'PR' then 'PR' end,
                                            case when substr(item,15,2) = 'DI' then 'DI' end
                                       from product
                                      where item = p.item
    where substr(item,11,2) = 'SA'
        or substr(item,13,2) = 'PR'
        or substr(item,15,2) = 'DI'Regards
    Etbin

  • How to send output from SQL script to the specified log file (not *.sql)

    ## 1 -I write sql command into sql file
    echo "SELECT * FROM DBA_USERS;">results.sql
    echo "quit;">>results.sql
    ##2- RUN sqlplus, run sql file and get output/results into jo.log file
    %ORACLE_HOME/bin/sqlplus / as sysdba<results.sql>>jo.log
    It doesn't work please advise

    $ echo "set pages 9999" >results.sql ### this is only to make the output more readable
    $ echo "SELECT * FROM DBA_USERS;" >>results.sql
    $ echo "quit" >>results.sql
    $ cat results.sql
    set pages 9999
    SELECT * FROM DBA_USERS;
    quit
    $ sqlplus -s "/ as sysdba" @results >jo.log
    $ cat jo.log
    USERNAME                          USER_ID PASSWORD
    ACCOUNT_STATUS                   LOCK_DATE  EXPIRY_DAT
    DEFAULT_TABLESPACE             TEMPORARY_TABLESPACE           CREATED
    PROFILE                        INITIAL_RSRC_CONSUMER_GROUP
    EXTERNAL_NAME
    SYS                                     0 D4C5016086B2DC6A
    OPEN
    SYSTEM                         TEMP                           06/12/2003
    DEFAULT                        SYS_GROUP
    SYSTEM                                  5 D4DF7931AB130E37
    OPEN
    SYSTEM                         TEMP                           06/12/2003
    DEFAULT                        SYS_GROUP
    DBSNMP                                 19 E066D214D5421CCC
    OPEN
    SYSTEM                         TEMP                           06/12/2003
    DEFAULT                        DEFAULT_CONSUMER_GROUP
    SCOTT                                  60 F894844C34402B67
    OPEN
    USERS                          TEMP                           06/12/2003
    DEFAULT                        DEFAULT_CONSUMER_GROUP
    HR                                     47 4C6D73C3E8B0F0DA
    OPEN
    EXAMPLE                        TEMP                           06/12/2003
    DEFAULT                        DEFAULT_CONSUMER_GROUPThat's only a part of the file, it's too long :-)

  • How exit for a script having set of pl/sql blocks and sql queries

    HI,
    I have set of blocks and sql queries in a script.
    In some cases I want to stop the excution of next statements and blocks.
    As in pl/sql block We can use return , in case of loop we can use exit, so what is to be use in case if sql script which contain set of blocks and sql queries.
    Thanks and Regards in Advance,

    Hi,
    how to exit from the script if confirm_to_continue is set to 'N'.
    i.e in this case I want the preceding statements not to be excuted.
    Please suggest.
    script:
    declare /*BLOCK NO1*/
    begin
    IF &&confirm_to_continue = 'N'
    THEN
    ---exit from from whole script
    RETURN; -- this will only exit from this block
    END IF;
    end;
    host IF EXIST &file_name (del &file_name) ELSE (echo missing)
    declare /*BLOCK NO 2*/
    begin
    end;
    /

  • Import from sl-script

    Hi,
    I was looking for a method to import a mapping or other objects from sql-script and found this nice sample:
    http://blogs.oracle.com/warehousebuilder/newsItems/viewFullItem$132
    unfortunately it seems to deal with an older version of OWB and I can't find such an import function in 10.2.x
    can somebody tell me how to import an easy sql-script into OWB ?
    Actually I am looking to build an easy DML-statement as a mapping, but can't find a method how to force the mapping performing only this particular operation like 'delete'.
    1 idea was to use lookup operator to do something easy like this:
    delete from tab_A
    wehre TAB_A.col1 in (select col2 from tab_B)
    But in OWB even easy things become pretty complicate and I can't find, how OWB must be driven to do such an easy operation.
    thanks for any hint, LaoDe

    Hi LaoDe,
    you may access source records with lookup operator - you can link fields from source table and from lookup operator to the same input group of any operator (for example FILTER or JOIN, etc.).
    In your case I recomend you to use splitter with three output groups:
    1) first group - for matched records for update TAB_A (condition - primary key of lookup table IS NOT NULL);
    2) second group - for not matched records for insert into TAB_ERR (condition - primary key of lookup table IS NULL);
    3) third group - for not matched records for delete from TAB_A (condition - primary key of lookup table IS NULL).
    So you should use TAB_A in this mapping three times (as source, as target for update, as target for delete).
    Don't forget to set target order loading (delete operation from TAB_A must be last).
    And maybe set Commit control to Correlated.
    Regards,
    Oleg

  • How can I read/write data files (text file) from PL/SQL Script

    I had an oracle forms pl/sql program to read/write a data file (text file). When this code is run on a command line as a PL/SQL script using the SQL*Plus I am getting an error:
    -- sample.sql
    DECLARE
      vLocation                 VARCHAR2(50)  := 'r:\';
      vFilename                 VARCHAR2(100) := 'sample.dat';
      vTio                   TEXT_IO.FILE_TYPE;
      vLinebuf               VARCHAR2(2000);
      vRownum               NUMBER        := 0;
      -- use array to store data FROM each line of the text file     
      TYPE           array_type IS VARRAY(15) OF VARCHAR2(100);
      vColumn      array_type := array_type('');
      PROCEDURE prc_open_file(p_filename IN VARCHAR, p_access IN VARCHAR2) is
      BEGIN
        vTio := TEXT_IO.FOPEN(vLocation||p_filename,p_access);
      EXCEPTION
        WHEN OTHERS then
          --  raise_application_error(-20000,'Unable to open '||p_filename);
          message(sqlerrm);pause;
      END;
      PROCEDURE prc_close_file is
      BEGIN
        IF TEXT_IO.IS_OPEN(vTio) then
           TEXT_IO.FCLOSE(vTio);
        END IF;
      END;
    BEGIN
      --extend AND initialize the array to 4 columns
      vColumn.EXTEND(4,1);
      prc_open_file(vFilename,'r');
      LOOP
          LTEXT_IO.GET_LINE(vTio,vLinebuf);
          vColumn(1)  := SUBSTR(vLineBuf, 1, 3);
          vColumn(2)  := SUBSTR(vLineBuf, 5, 8);
          vColumn(3)  := SUBSTR(vLineBuf,10,14);     
          Insert Into MySampleTable
          Values
            (vColumn(1), vColumn(2), vColumn(3));
          EXIT WHEN vLinebuf IS NULL;
       END LOOP;
       prc_close_file;
    END;
    SQL> @c:\myworkspace\sql\scripts\sample.sql;
    PLS-00201: identifier 'TEXT_IO.FILE_TYPE' must be declaredIt works on the oracle forms but not on the SQL*Plus. Is there an alternative method using a PL/SQL script? A simple sample would help. Thanks.

    Did you ever noticed the search box at the right side of the forum?
    A quick search (limited to this years entries) brought up this thread for example
    Re: UTL_FILE Examples

  • Error in calling SQL plus program with parameter from Shell script

    This is my Shell script. I am trying to call in the SQL plus program with the parameter and the shell script is registered as a concurrent program.
    PARAMETERS=`echo $1 |tr -d '\"'`
    DB_USER_ID=`echo $PARAMETERS|cut -d" " -f3|cut -d"=" -f2`
    CONN_STRING=$DB_USER_ID
    REQ_DATE=`echo $PARAMETERS|cut -d" " -f9|cut -d"=" -f2`
    timestamp=`date +%m-%d-%y-%H:%M:%S-%Z`
    timestam=`date +%y-%m-%d`
    sqlplus -s $CONN_STRING @ar_statement.sql $REQ_DATE
    chmod 755 statement.sh
    . statement.sh
    My Sql plus program is like this.
    set pagesize 0
    set heading off
    set feedback off
    spool $GEC_TOP/log/ge_ar_statement.sh
    select output_file_name
    from fnd_concurrent_requests
    where trunc(actual_completion_date) = '&2';
    spool off;
    exit;
    When i run the concurrent program, i am getting the following error:
    ar_statement: line 14: REQ_DATE: command not found
    Enter value for 2:
    User requested Interrupt or EOF detected.
    ar_statement.sh: line 1: Enter: command not found
    ar_statement.sh: line 2: User: command not found
    ar_statement
    Program exited with status 127
    I am not strong at Unix Porgamming and i would request someone who can
    help me out as soon as possible.
    I need this solution quickly and thank everyone in advance.
    Thanks.

    Can you put your coding between code statements, like shown in the FAQ. It will be easier to read.
    Looking at your script, my first guess is that crontab will not find your sqlplus since your script does not have $HOME/bin in the $PATH. From what I understand, running .profile in your script will not work either because variables are exported to sub-shells, not to the shell above. You can call your script with a dot like . ./script which means that the script will run like it was typed at the command prompt. But it will be less confusing to define appropriate variables in the script. eg.
    ORACLE_SID=my_instance_name
    ORACLE_HOME=/my_path_to_oracle_home_directory
    LD_LIBRARY_PATH=$ORACLE_HOME/lib
    PATH=$ORACLE_HOME/bin:$PATH
    I remember some slightly different way of coding to handle the sqlplus return codes.
    For instance:
    sqlplus -s /nolog > /dev/null <<-EOF
    connect system/manager
    @ssm.sql
    whenever oserror exit failure
    whenever sqlerror exit failure
    EOF
    sql_err=$?
    if [ $sql_err -ne 0 ]; then
       echo "FAILURE"
    else
       echo "SUCCESS"
    fiThe - in -EOF supresses tab's
    Using connect will prevent ps from showing your login credentials
    In some versions of bash the ending EOF needs to be at the beginning of the line to work.
    Edited by: waldorfm on Jul 14, 2010 7:05 PM
    complaining about putting code between code delimiters and forgot myself ;-)
    Edited by: waldorfm on Jul 14, 2010 7:08 PM
    Btw, if you "source" a script running it like . .script, than an exit in that script will log you out.

  • ORA-27369 Exit-Code: 255 when executing sql script as job

    Dear all
    I'd like to find and compile all invalid objects in an instance. This should be done every day as a scheduled job with the use of DBMS_SCHEDULER.
    For this, I set up the following sql-script:
    ---------start script--------------
    set heading off;
    set feedback off;
    set echo off;
    Set lines 999;
    Spool /tmp/run_invalid.sql
    select
    'ALTER ' || OBJECT_TYPE || ' ' ||
    OWNER || '.' || OBJECT_NAME || ' COMPILE;'
    from
    dba_objects
    where
    status = 'INVALID'
    spool off;
    set heading on;
    set feedback on;
    set echo on;
    @/tmp/run_invalid.sql
    exit
    ------ end script ----
    The script ist working well when executed manualy via sqlplus. As you can see, it spools the commands to a second file (run_invalid.sql) which is the beeing executed to compile the invalid objects found.
    I now want to schedule this script via DBMS_SCHEDULER (running the job every day at 7AM). Creation of the job:
    BEGIN
    DBMS_SCHEDULER.CREATE_JOB (
    job_name => 'compile_invalid_objects',
    job_type => 'EXECUTABLE',
    job_action => '/home/oracle/scripts/sql/compile_invalid_objects.sql',
    start_date => trunc(sysdate)+1+7/24,
    repeat_interval => 'trunc(sysdate)+1+7/24',
    enabled => TRUE,
    comments => 'SQL-Script, und invalid objects zu finden und zu kompilieren'
    END;
    Manualy execute and error message:
    BEGIN
    DBMS_SCHEDULER.RUN_JOB (job_name => 'compile_invalid_objects',
    use_current_session => true);
    END;
    FEHLER in Zeile 1:
    ORA-27369: Job vom Typ EXECUTABLE nicht erfolgreich mit Exit-Code: 255
    ORA-06512: in "SYS.DBMS_ISCHED", Zeile 150
    ORA-06512: in "SYS.DBMS_SCHEDULER", Zeile 441
    ORA-06512: in Zeile 2
    --> Sorry for this, I'm using german localized oracle.
    Unfortunately, it seems that only Shell-Scripts can be scheduled when using job_type='EXECUTABLE'. Can you confirm this?
    BTW: The script is chmoded to 777, therefore it can't be a permission problem.
    Is there maybe another solution with one single script using dbms_output functionality and run the script in a loop?
    To complete my post, here are the commands used to create and test the job:
    BEGIN
    DBMS_SCHEDULER.CREATE_JOB (
    job_name => 'compile_invalid_objects',
    job_type => 'EXECUTABLE',
    job_action => '/tmp/compile_invalid_objects.sql',
    start_date => trunc(sysdate)+1+7/24,
    repeat_interval => 'trunc(sysdate)+1+7/24',
    enabled => TRUE,
    comments => 'SQL-Script, und invalid objects zu finden und kompilieren'
    END;
    Thanks for your help
    Casi

    You could more simply use $ORACLE_HOME/dbms/admin/utlrp.sql

  • Passing params from SQL file to Shell Script and then from Shell to SQL Fil

    Afternoon guys,
    Have a fun question for all you gurus in shell scripting out there. I have a shell script that is calling 2
    different SQL programs. My objective is to pass a variable called request_number from one sql program
    to the shell script and then from the shell script back to another SQL program. I will explain why I
    need this to happen.
    Here is what the shell script looks like which calls sql programs student_load_a.sql and
    student_load_b.sql. Student_load_a.sql basically creates the control file (.ctl) which is needed for the
    SQL*Loader and then student_load_b.sql reads the table that was just loaded and does the main
    processing. My main objective here is to be passing the request_number which is being generated
    using an Oracle Sequence in student_load_a.sql and using this generated number in my main
    processing in student_load_b.sql to select records from the table based on request_number.
    Any ideas ?Any help or recommendations is welcome and appreciated.
    *1. Shell Script*
    # Accept system input parameters
    p_user_id=$1
    p_job_id=$2
    # Create control files for sqlload
    sqlplus.exe -s $p_user_id @$STUDENT_PATH/student_load_a.sql $p_job_id
    exit_status=$?
    # Do sqlloads
    sdesqlldr.exe userid=$p_user_id control=student_load-$p_job_id.ctl \
                                                 log=student_load-$p_job_id.log \
                                                 bad=student_load-$p_job_id.bad
    exit_status=$?
    # Main processing
    # sqlplus.exe -s $p_user_id @$STUDENT_PATH/student_load_b.sql $p_user_id $p_job_id $p_request_number
    sqlplus.exe -s $p_user_id @$STUDENT_PATH/student_load_b.sql $p_user_id $p_job_id
    exit_status=$?
    exit 0*2. student_load_a.sql (Would like to pass back the Sequence Number back to shell script and then use in student_load_b.sql*
    -- Accept system input parameters
    define p_job_id = &1
    spool student_load-$p_job_id.ctl
    select
    'append into table TMP_STUDENT_LOAD
    FIELDS TERMINATED BY '','' optionally enclosed by ''"''
    trailing nullcols
    (request_number CONSTANT ' || '''' || request_number_seq.nextval || ''',
    student_id)'
    from   dual
    spool off;
    exit 0;
    {code}
    *3. student_load_b.sql (This is a big file so I am only adding code that is relevant for the SQL)*
    {code}
    declare
      v_request_number    number(6);
      v_student_id                  number(7);
      cursor cur_student_load is
        select  student_id
        from   TMP_STUDENT_LOAD
        where  request_number = v_request_number
        order by 1;
    begin
        v_user_id := '&1';
        v_job_id := &2;
        -- This is the variable I would like to be be passing from shell script to student_load_b.sql
        -- v_request_number = '&3';
         open  cur_student_load;
         fetch cur_student_load into v_student_id;
          exit when cur_student_load%notfound;
          .... more logic of if then else in here
         close cur_student_load;
    end;
    {code}
    Edited by: RDonASnowyDay on Jan 29, 2010 4:03 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    How come you are mixing WinDoze script (*.exe) with Unix?
    You are aware that you will be passing the password along with the user id to the second sql script?
    I will assume Unix ksh:
    # Accept system input parameters
    p_user_id=$1
    p_job_id=$2
    # Create control files for sqlload
    p_seqno=`sqlplus -s $p_user_id @$STUDENT_PATH/student_load_a.sql $p_job_id`
    exit_status=$?
    # Do sqlloads
    sqlldr userid=$p_user_id control=student_load-$p_job_id.ctl \
           log=student_load-$p_job_id.log \
           bad=student_load-$p_job_id.bad
    exit_status=$?
    # Main processing
    # sqlplus -s $p_user_id @$STUDENT_PATH/student_load_b.sql $p_user_id $p_job_id $p_request_number
    sqlplus -s $p_user_id @$STUDENT_PATH/student_load_b.sql \
               $p_user_id $p_job_id $p_seqno
    exit_status=$?
    exit 0And the first sql script would look like this:
    -- student_load_a.sql
    -- Accept system input parameters
    set echo off pages 0 feed off lin 80 trims on ver off
    def p_job_id = &1
    col seqno NEW_VALUE seqno
    select request_number_seq.nextval seqno from dual;
    set term off
    spool student_load-$p_job_id.ctl
    select
    'append into table TMP_STUDENT_LOAD
    FIELDS TERMINATED BY '','' optionally enclosed by ''"''
    trailing nullcols
    (request_number CONSTANT ''&&seqno'',
    student_id)'
    from   dual
    spool off;
    exit 0;
    {code}
    :p                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

Maybe you are looking for

  • 4th gen iPod turned off and won't turn back on.

    So, earlier today I had my iPod touch (4th gen) plugged into my electronic drum kit through a double sided auxillary cable. Nothing out of the usual. I turned it to a certain song I felt like jamming to at the time and it froze. It was a weird type o

  • Ipod first generation

    i am just in the process of buying and ipod first gen. The problem is i have a windows commputer not a mac, and that ipod was formated for just mac. now i hurd that there is some kind of way that you can make the first gen compatiable with windows. A

  • How to add item in advnace search LOV  of OA frame work ?

    HI, I have one requirement to add one new item in existing lov of advance search of vertical view in OA framework which is seeded.Through the Form personalisation I have created Criteria Row: (MscCreationdate_row) in which i have given ID value as Ms

  • Smartform problem with field in table

    Hi everyone, I have  a strange issue. I created a table within a smartform. That table has a row with few fields. Somehow, value of field 5 appears in field 4 (near value of field 4). Of course, value of field 5 is meant to be displayed in its own co

  • Unable to access the ESwork place

    Hi While access the service which is in ESwork place , prompting username and password. 2day only I made registestration to the ESworkplace still i am unable to login, will they send any mail with new user id or  SDN userId used for login to the ESwo