Calling sql script in plsql procedure

Hello,
I have a sql script named mytest.sql and i want to execute this from a stored procedure.
following is the contents of this script
spool d:\mytestsql.txt
select * from tab;
spool off
Actually i want my sql script to run daily to export some tables data.
I can execute this script from a sql prompt but i want to run it from enterprise manager.
I am using oracle 10gR2 on windows2000 system.
Any idea about scheduling the sql script to run automatically??
How to execute this sql script from a plsql procedure??
Thanks

Hi all,
Thanks for all the replies. I have found the solution with external procedures.
Following is the complete step by step guide.
1. Create the OSCommand Java Class using the following statement:
connect as any user:
create or replace and compile java source named oscommand as
import java.io.*;
public class OSCommand{
public static String Run(String Command){
try{
Runtime.getRuntime().exec(Command);
return("0");
catch (Exception e){
System.out.println("Error running command: " + Command +
"\n" + e.getMessage());
return(e.getMessage());
2. Create the following Wrapper Function using the following statement:
CREATE or REPLACE FUNCTION OSCommand_Run(Command IN STRING)
RETURN VARCHAR2 IS
LANGUAGE JAVA
NAME 'OSCommand.Run(java.lang.String) return int';
3. connect as sys
Execute dbms_java.grant_permission( 'FKHALID','SYS:java.io.FilePermission', '<<ALL FILES>>','execute');
execute dbms_java.grant_permission( 'FKHALID','SYS:java.lang.RuntimePermission', 'writeFileDescriptor', '*' );
execute dbms_java.grant_permission( 'FKHALID','SYS:java.lang.RuntimePermission', 'readFileDescriptor', '*' );
commit;
note: here fkhalid is the oracle user.
connect as fkhalid user:
Declare
expdp_cmd Varchar2(2000);
Begin
expdp_cmd := OSCommand_Run('cmd /c sqlplus fkhalid@mtcedwt/pwd @d:\ORA_DUMPS\mydbexp.sql');
DBMS_OUTPUT.Put_Line(expdp_cmd);
End;
In Unix
Set Serverout On
Declare
x Varchar2(2000);
Begin
x := OSCommand_Run('/home/test/myoscommand.sh')
DBMS_OUTPUT.Put_Line(x);
End;
I will check the dbms_scheduler also and will let you know the results.
Thanks

Similar Messages

  • How to call SQL Script in DBMS_SCHEDULER

    How to call SQL Scripts in DBMS_SCHEDULER?
    Things I got working
    1) Successfully created and tested a PL/SQL that was created under SQL Workshop->SQL Scripts (I named it 'TEST'). I was able to run this no problem.
    2) Successfully created a DBMS_SCHEDULER that runs every minutes. (See below)
    begin
      dbms_scheduler.create_job(
        job_name => 'myjob',
        job_type => 'plsql_block',
        job_action => 'null;',
        start_date => '19-JUL-11 03.10.00 PM', /* Remember to use the DB time, not your local time if not specifying a timezone */
        repeat_interval => 'freq=minutely',
        enabled => true);
    end;The problem i am having is to make the PL/SQL script (named 'TEST') runs every minute. Its probably very easy to do that but i dont seems like finding any examples online.
    I tried replacing the job_action attribute to " job_action => 'begin TEST; END;', " However, that did not work.
    I am stuck here for couple hours already, any clues would be great :)
    Thanks in advance
    John
    Application Express 4.1.0.00.32
    Edited by: John Lau on Aug 14, 2012 12:47 PM
    Edited by: John Lau on Aug 14, 2012 12:48 PM

    The PL/SQL is pretty long, I would like to call it from a different location rather then putting the whole coding as part of the argument. Sounds like I should be looking into procedure package in database?
    I will do some more research on procedure package, how to create one and how to call from it.
    Thanks
    John

  • Calling java classes from plsql procedures

    I'm attempting to call java classes from plsql procedures which will create cmsdk users, folders, groups etc, however when I attempt to load a java class into the oracle schema using the command:
    loadjava -user user/password@database -resolve classname.class
    It generates error messages to the effect that classes (cmsdk classes) required by the class cannot be found. The class is loaded and marked with the status "invalid". Is it therefore necessary for me to load the cmsdk packages into the schema?
    Cheers
    David

    Using CMSDK Java API within the database has never been supported
    (see Problems loading IFS's java class into database
    When we needed to invoke CMSDK code from our PL/SQL code, we used one of two approaches:
    (1) use advanced queues to send requests to an external Java program (the CMSDK code, running outside the database) and receive the results back (asynchronous choice); or
    (2) make an HTTP request to a Java servlet (the CMSDK code, running in some Java web container like iAS) and get the response back in some custom format (XML or something) (synchronous choice).
    It seems to me that the CMSDK Java API was designed to be used only in middle-tier, not in database tier.
    Regards,
    Daniel.

  • Calling SQL * LOADER  in stored procedure

    Hi Experts,
    Can we call sql*loader in stored procedures? . If yes , please let me know the syntax.
    Any help will be highly appreciated.
    Thanks.

    You can also use dbms_schedular to execute any shell or batch file - i guess ->
    BEGIN
      -- UNIX
      DBMS_SCHEDULER.create_job(
        job_name             => 'unix_command_job',
        job_type             => 'EXECUTABLE',
        number_of_arguments  => 1,
        job_action           => '/bin/ls',
        auto_drop            => FALSE,
        enabled              => FALSE);
      DBMS_SCHEDULER.set_job_argument_value('unix_command_job',1,'/tmp');
      DBMS_SCHEDULER.set_attribute('unix_command_job', 'credential_name', 'TIM_HALL_CREDENTIAL');
      DBMS_SCHEDULER.set_attribute('unix_command_job', 'destination', 'marge.localdomain:65001');
      DBMS_SCHEDULER.enable('unix_command_job');
    END;For details ->
    http://www.oracle-base.com/articles/11g/SchedulerEnhancements_11gR1.php
    http://www.oradev.com/dbms_scheduler.jsp
    http://www.psoug.org/reference/dbms_scheduler.html
    Regards.
    Satyaki De.

  • To automate the SQL scripts using PLSQL Code

    Hi All,
    I have 20 database server (11.2.0.3) hosted on  unix and Windows platforms.
    Every day I have to kill inactive sessions from all the these 20 database servers. So I have made a below script::
    connect sys/&&sys_password@&&tns_database_name as sysdba
    SPOOL E:\DELETE_INACTIVE_SESSIONS.SQL
    set PAGESIZE 1000
    set LIN 5000
    SET ECHO OFF;
    SET FEEDBACK OFF;
    SET HEADING OFF;
    select 'alter system kill session '||'`'||SID||','||SERIAL#||'`'||' immediate;'  from v$session where status='INACTIVE' and username in ('OSS_DICTIONARY','ADMINISTRATOR');
    SPOOL OFF;
    @@E:\DELETE_INACTIVE_SESSIONS.SQL
    Is there any way so that this execution of script can be automated in PLSQL code for 20 servers so and that code could be put in batch file for execution(i.e. can be execute through batch file from my windows laptop).
    Thanks

    Shrma wrote:
    Is there no way to handle the sql scripts in PLSQL code?
    Well, remember that PL/SQL is executed on a specific server by a certain user so you are already connected when executing a PL/SQL code.
    You could actually use a SQL Plus script to connect to different servers using connect and run your script.
    i.e.:
    SQL> connect sys/pwd_server1@db_server1
    SQL> @killinactive.sql
    SQL> connect sys/pwd_server2@db_server2
    SQL> @killinactive.sql
    But it does not make so much difference with my previous solution.
    Please explain exactly what you would like to do.
    Regards.
    Al

  • Shell script to call sql script

    Hi All,
    I have a application server and want to make a shell script to call sql script.
    Please let me know how to do the same.
    Regards
    Kumar

    What is the platform you are using and you can give the path of the sql script in your shell script as follows
    1.)first create .sql file...let it is table.sql and has the contents ...
    create table test(x1 varchar2(20),x2 number(4),x3 date)
    exit;
    (2.) write a shell script...like table.sh in vi editor
    Here login is scott/tiger@sid, or apps/apps@sid or whatever you know valid schema
    echo enter the login
    read login
    sqlplus -s $login @table
    (3.)run the script
    $ sh table.sh
    it will create the table in your particular schema

  • Calling perl script from PLSQL

    Hi All,
    I have created Java stored procedure and oracle function to execute the os commnad, this works fine for calling batch scripts but when i used same function to call perl script,
    like how we call in batch script
    perl <script name> the sql gets hanged.
    Is it possible to call perl like this?
    or is their any other way to call from plsql
    Thanks Chandra

    Are you able to run that perl script at DOS command line?
    Did you call the perl script directly from the java proc or you put the perl command line in a DOS .BAT scirpt and called that from the java proc?

  • 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.

  • Calling sql script from shell script

    Hi,
    I know this question has been asked many time in various forums, but I tried many combinations and not able to figure out what I'm missing.
    Basically - I'm trying to call a sql script from a shell script.
    This is my sql script (plsql.sql) -
    DELCARE
    v_empno NUMBER := '&empno';
    BEGIN
    select ename,sal from emp where empno = v_empno;
    dbms_output.put_line('Inside the plsql file');
    END;
    This is my unix shell script - I'm caling the plsql.sql file with the parameter passed(97882). I don't get any output. at least I should be able to view the dbms output if not for the sql query inside the sql script.
    #!/usr/bin/ksh
    sqlplus -s sam/olo01 << HERE
    @plsql.sql 97882;
    HERE
    What is it I am missing ?

    Using your scripts (and having to create and populate a table myself, that would have what your select statement implies),
    oracle:oklacity$ cat plsql.sql
    DELCARE
    v_empno NUMBER := '&empno';
    BEGIN
    select ename,sal from emp where empno = v_empno;
    dbms_output.put_line('Inside the plsql file');
    END;
    oracle:oklacity$ cat doit.sh
    #!/usr/bin/ksh
    sqlplus -s sam/olo01 << HERE
    @plsql.sql 97882;
    HERE
    oracle:oklacity$ ./doit.sh
    SP2-0042: unknown command "DELCARE" - rest of line ignored.
    SP2-0734: unknown command beginning "v_empno NU..." - rest of line ignored.
    oracle:oklacity$
    This is the kind of information you should have put in your opening post.

  • Oracle BI 11.1.1.7.1: Calling BI webservices from Plsql Procedure: ORA-29532: Java call terminated by uncaught Java exception: java.lang.NoClassDefFoundError

    Hi,
         I have a requirement of calling BI webservices from Plsql stored procedure. I generated all my wsdl java classes and loaded them into the database. However, when I tried to call one of my java class using stored procedure, it is giving me"ORA-29532: Java call terminated by uncaught Java exception: java.lang.NoClassDefFoundError".
    *Cause:    A Java exception or error was signaled and could not be
               resolved by the Java code.
    *Action:   Modify Java code, if this behavior is not intended.
    But all my dependency classes are present in database as java class objects and are valid. Can some one help me out of this?

    Stiphane,
    You can look in USER_ERRORS to see if there's anything more specific reported by the compiler. But, it could also be the case that everything's OK (oddly enough). I loaded the JavaMail API in an 8.1.6 database and also got bytecode verifier errors, but it ran fine. Here are the errors I got when loading Sun's activation.jar, which ended up not being a problem:
    ORA-29552: verification warning: at offset 12 of <init> void (java.lang.String, java.lang.String) cannot access class$java$io$InputStream
    verifier is replacing bytecode at <init> void (java.lang.String, java.lang.String):12 by a throw at offset 18 of <init> void (java.lang.String, java.lang.String) cannot access class$java$io$InputStream
    verifier is replacing bytecode at <init> void (java.lang.String, java.lang.String):18 by a throw at offset 30 of <init> void (java.lang.String, java.lang.String) cannot access class$java$io$InputStream
    verifier is replacing bytecode at <init> void (java.lang.String, java.lang.String):30 by a throw
    Hope this helps,
    -Dan
    http://www.compuware.com/products/devpartner/db/oracle_debug.htm
    Debug PL/SQL and Java in the Oracle Database

  • File Ownership while executing sql script from stored procedure

    We have a test_command.sql script which is spooling the result into a file. From database we have one Store Procedure(run_sql) which is
    calling and executing the .sql script.
    When we are calling the sql script directly from the database, i e SQL > @/dccops/test_command.sql it is creating the
    file under the Ownership of OS user which is connected to the system.
    The problem we are facing is when we are executing the stored procedure i e exec run_sql(), the file is creating under
    Oracle User.
    Could u please suggest me a solution inorder to create the output file under the user who is logged to the OS.

    First of all, your usage of IM speak is NOT appreciated. Please do not address anyone as if they were a 12-year old.
    'Our Applcation is in C. So we have to call the procedure to run the sql script.'
    This is just utter nonsense!
    Oracle has Pro*C which allows Embedded SQL in C. There is also OCI (Oracle Call Interface) to call Oracle directly in C, and there is OCCI, to do the same in C++.
    Apart from that, Oracle has Ole DB for Windows platforms, to allow for a .NET compatible interface to Oracle.
    There is NO NEED AT ALL to call PL/SQL to run a SQL script.
    Sybrand Bakker
    Senior Oracle DBA

  • Migrating SQL Script to stored procedure...

    I created a SQL script file to run in SQLPlus to
    generate a fixed-format text file (See EDI_PrepForSend
    below)
    How do i do the same thing in a stored
    package/procedure? Can I utilize the
    script I already have working? I need to
    do it in a stored procedure because I need
    to do dynamic queries.
    TIA
    Chuck Plinta
    [email protected]
    ++++++++++++++++++++++++++
    -- EDI_PrepForSend.sql
    SET CONCAT '#';
    SET ESCAPE OFF;
    SET TERM OFF
    -- Set's for flat file
    SET NEWPAGE 0
    SET SPACE 0
    SET LINESIZE 50
    SET PAGESIZE 0
    SET ECHO OFF
    SET FEEDBACK OFF
    SET HEADING OFF
    SET VERIFY OFF
    SPOOL o:\ClientData\EDI-Send\&2\EDI-HCFA-Dtl-&1-&3.txt
    COLUMN MC_Number FORMAT A15 HEADING MC_Number
    COLUMN MC_Line_Number FORMAT A3 HEADING Ln#
    COLUMN MC_CPT_Code FORMAT A5 HEADING Code
    COLUMN MC_CPT_Modifier FORMAT A2 HEADING Mod
    COLUMN MC_FDOS FORMAT A8 HEADING FDOS
    COLUMN MC_LDOS FORMAT A8 HEADING LDOS
    COLUMN MC_Line_Charge FORMAT 99999.99 HEADING Charge
    SELECT MC.ICN MC_Number,
    '???' MC_Line_Number,
    MC.CPT_Code MC_CPT_Code,
    MC.CPT_Modifier_1 MC_CPT_Modifier,
    TO_CHAR(MC.First_DOS,'YYYYMMDD') MC_FDOS,
    TO_CHAR(MC.Last_DOS,'YYYYMMDD') MC_LDOS,
    MC.Charge MC_Line_Charge
    FROM &1.Decision_Support DS,
    &1.Medical_Claims MC
    WHERE DS.Reprice_Status = 'U' AND
    MC.CID = DS.CID
    ORDER BY MC.ICN, MC.CID;
    SPOOL OFF

    You need to put your select statement in a parameterised function that returns a REF CURSOR. This is all well documented in the PL/SQL users guide.
    Then you amend your SQL*PLUS script to call the function
    VAR rc REFCURSOR
    EXEC :rc := yr_function('&1')
    PRINT rc
    Cheers, APC

  • Calling sql script in a folder

    Hi All,
    I'm calling a SQL script from a root SQL script which is present in a sub folder.
    root.sql
    Prompt Loading FULL_RECOMPILE.SQL
    SET DEFINE OFF
    @@Utils\FULL_RECOMPILE.SQL
    SET DEFINE ON
    Show errors
    commit;When I run the script I'm getting the following error.
    SP2-0310: unable to open file "UtilsFULL_RECOMPILE.SQL".
    I tried using forward / (@@Utils/FULL_RECOMPILE.SQL) and the script executed succesfully.
    Is there anyway I can execute the above script by using a backward slash?
    BANNER
    Oracle9i Enterprise Edition Release 9.2.0.8.0 - 64bit Production
    Thanks,
    guru
    Edited by: guru on 30-Jun-2010 05:54

    Your requirement seems to be executing the script present in the path:
    *./Utils/FULL_RECOMPILE.SQL*
    Is there anyway I can execute the above script by using a backward slash?Whats the need for using a backslash? Unix paths are separated by forward slash in contrast to windows.

  • BI Publisher 11g - calling SQL Server 2005 stored procedure error

    Hi experts
    I have been calling succesfully an SQL server 2005 stored procedure for the data model of a BI publisher report in 10g, passing it a customerNo parameter.
    EXEC     [dbo].[usp_WelcomeLettersConsumerNo]
              @CustomerNo = :sCustomerNo
    However it does not work in 11g I get the error:
    [Hyperion][SQLServer JDBC Driver][SQLServer]Incorrect syntax near the keyword 'is'.
    which is frustrating as there is no 'is' in the statement (perhaps it is picking up :s?) - I wonder does anyone know if there has been a change in 11g that may be causing this?
    cheers
    Tim

    Hi experts
    I have been calling succesfully an SQL server 2005 stored procedure for the data model of a BI publisher report in 10g, passing it a customerNo parameter.
    EXEC     [dbo].[usp_WelcomeLettersConsumerNo]
              @CustomerNo = :sCustomerNo
    However it does not work in 11g I get the error:
    [Hyperion][SQLServer JDBC Driver][SQLServer]Incorrect syntax near the keyword 'is'.
    which is frustrating as there is no 'is' in the statement (perhaps it is picking up :s?) - I wonder does anyone know if there has been a change in 11g that may be causing this?
    cheers
    Tim

  • Running a sql script from stored procedure

    Hi everyone!
    Has anybody tell me how to execute a sql script from a stored
    procedure!
    Thanks in advance!
    Sasa

    >
    Hi everyone!
    Has anybody tell me how to execute a .sql file from a stored
    procedure!
    Thanks in advance!
    Sasa Sorry, a .sql file!!

Maybe you are looking for

  • HT201263 how do you update your i pod touch 4th generation

    How do you update your i pod

  • Not syncing movies or music

    Hi all, I am having problems with my daughter's Ipod (3rd gen). IT will not sync music or movies, but will sync games with no problems. Have restarted the computer, reset the ipod both through itunes and on the ipod. Any suggestions gratefully receiv

  • Samsung monitor (2253LW 22") & iBook G4

    I saw this Samsung monitor at Costco (Samsung 2253LW 22" 1680x1050 native resolution), it has both DVI & VGA connections. It's got really great reviews from a lot of websites. I would be using the VGA connector. I guess the resolution on my iBook is

  • Creating RSS feeds

    How do you create RSS feeds? I am building a school site that would like to use RSS feeds. Thanks! -Dan

  • Need F Spec For MM.

    Hello Everyone,         I am assigned to do a mini project on a bike manufacturing industry where I need to fetch the FS of all the modules. I particularly need the main attributes that are required from MM. As I am not getting the workflow of MM ple