Unix sql script

hi,
I need some help if possible
I have the folloiwng script
select count(*) from dba_users where account_status !='OPEN'
and username not in (
'PROD_HCUST_HK',
'MDSYS',
'SCOTT',
'WMSYS',
'CTXSYS',
'ANONYMOUS',
'OUTLN',
'MGMT_VIEW',
'SI_INFORMTN_SCHEMA',
'ORDSYS',
'EXFSYS',
'DMSYS',
'ORACLE_OCM',
'TSMSYS',
'MDDATA',
'DIP',
'SYSMAN',
'XDB',
'ORDPLUGINS',
'OLAPSYS'
;normally the result of count(*) will be '0'
I need to wrap this in a unix script to be able to then get a result so that I can if the value of count(*) is > 0 then I can get an alert from grid control.
regards
Alan

Hi Alan,
One way I do this is using a shell script to run an .sql file with your code in it. i.e. have a file called selectAll.sql with whatever query you want to run and then I use a shell script in the following fashion.
The SQL that I use selects one column per row.
This is a /bin/bash script that is run as root, hence the su - oracle stuff
MEDIA=`su - oracle -c ". ~/.bash_profile; sqlplus username/password@database @/u01/sql/selectAll -S | grep ':' | grep -v 'Connected' | grep -v 'SQL'"`
#Use newline as separator
OIFS=$IFS
IFS=;
#print one line per MIB variable
for text in $MEDIA; do
  echo $text | sed s/\://
doneHope this helps,
Conor

Similar Messages

  • Spool Russian Characters from a unix(AIX) sql script

    Hi All,
    I have a problem selecting and spooling a column whose characters are in russian to a flat file. If I use oracle sql developer, the data comes out right, e.g
    Р-Н ТАШКЕНТ
    However is i try to run the same select from a unix sql script and spool the results, I get some gibberish like:
    ò-î ôáûëåîô or a chain of question marks ?????????
    select * from nls_database_parameters gives:
    NLS_LANGUAGE=AMERICAN
    NLS_TERRITORY=AMERICA
    NLS_CHARACTERSET=UTF8
    NLS_NCHAR_CHARACTERSET=AL16UTF16
    I have tried exporting the environment variable using these various options individially to no avail:
    export NLS_LANG=RUSSIAN_CIS.CL8MSWIN1251
    RUSSIAN_RUSSIA.RU8PC866
    RUSSIAN_RUSSIA.CL8KOI8R
    RUSSIAN_RUSSIA.CL8MACCYRILLICS
    RUSSIAN_RUSSIA.RU8PC855
    RUSSIAN_RUSSIA.RU8BESTA
    RUSSIAN_RUSSIA.CL8ISO8859P5
    Please help.
    Thanks,
    Edited by: HouseofHunger on Apr 12, 2012 4:02 PM

    Os version: AIX 6.1.0.0
    Database version: Oracle Database 10g Enterprise Edition Release 10.2.0.5.0 - 64bit
    with the default values for NLS_LANG, I run sqlplus
    sqlplus user/password@oracle_sid
    select column_name from table_name;
    and the output is:
    column_name
    I exit and export NLS_LANG=RUSSIAN_CIS.CL8ISO8859P5
    go back into sqlplus and run the same query as above, and the output is
    column_name
    À-½ °Ⱥµ½Â
    À-¾½ ÃÀ°ǸÀǸºÁº¸¹
    °Ⱥµ½Â
    °Ⱥµ½Â
    ¾»Â¸½¾¹ À-¾½
    ³ ±µº°±°´
    ΠǸÀǸºÁº¸¹ À-½ ÷±µº¸ÁÂ
    Ä°À³¾½°
    Ϻº°Á°À°¹Áº¸¹
    °Ⱥµ½Â
    Á°¼°Àº°½´
    So it seems the output I get is somehow influenced by the value of environment variable NLS_LANG, so it may be that either I need the correct value for this environment variable or I need some config on the OS level.....?
    Also the command locale -a gives following output - I am not very good on locales, so it maybe that the russian local isn't installed...?
    $ locale -a
    C
    POSIX
    en_US.8859-15
    en_US.ISO8859-1
    en_US
    Thanks

  • Passing UNIX command in SQL Script

    Hi,
    I am writing a sql-script in unix.
    The logic is as below:
    SELECT flag FROM dummy_table;
    If flag = Y Then
    cp ./abc.txt $HOME/abc.txt
    Else
    SELECT id, roll FROM employees;
    Please help me out.
    Thanks and Regards,
    Tony

    I did that way:
    Under SYS create the following procedure:
    CREATE OR REPLACE PROCEDURE SYS.LINUX_RUN (PATH     IN     VARCHAR2,
                                               result      OUT VARCHAR2)
    IS
       script_file   VARCHAR2 (40) := 'my-temp-script.sh';
       script_data   VARCHAR2 (4000);
       MyFile        UTL_FILE.file_type;
       d             VARCHAR2 (4000);
       dump_file     VARCHAR2 (40) := '/tmp/my-temp-file.dat';
       dump_type     UTL_FILE.file_type;
    BEGIN
       pms.post_calls;
       -- Open file
       MyFile := UTL_FILE.fopen ('TMP', script_file, 'w');
       -- Write data to file
       script_data := PATH || ' > ' || dump_file;
       UTL_FILE.put_line (MyFile, script_data, FALSE);
       -- Close file
       UTL_FILE.fflush (MyFile);
       UTL_FILE.fclose (MyFile);
       -- Purge old logs, no fun anyway
       DBMS_SCHEDULER.purge_log (JOB_NAME => 'TEST');
       -- Execute script
       -- The job is created as disabled as
       -- we execute it manually and will
       -- drop itself once executed.
       DBMS_SCHEDULER.create_job (job_name              => 'TEST',
                                  job_type              => 'EXECUTABLE',
                                  job_action            => '/bin/sh',
                                  number_of_arguments   => 1,
                                  start_date            => SYSTIMESTAMP,
                                  enabled               => FALSE);
       DBMS_SCHEDULER.set_job_argument_value ('TEST', 1, '/tmp/' || script_file);
       DBMS_SCHEDULER.enable ('TEST');
       -- Wait for the job to be executed
       -- usually done within 1 second but
       -- I set it to 2 just in case.
       DBMS_LOCK.sleep (2);
       -- Open the output file and
       -- print the result.
       dump_type := UTL_FILE.fopen ('TMP', dump_file, 'r');
       UTL_FILE.get_line (dump_type, d);
       result := d;
       LOOP
          BEGIN
             UTL_FILE.get_line (dump_type, d);
             DBMS_OUTPUT.put_line (d);
          EXCEPTION
             WHEN OTHERS
             THEN
                EXIT;
          END;
       END LOOP;
       UTL_FILE.fclose (dump_type);
       -- Clean up our temp files
       UTL_FILE.fremove ('TMP', script_file);
       UTL_FILE.fremove ('TMP', dump_file);
    END;
    /And grant execute on this procedure to end user.
    Then under granted user you can use this procedure in your PL/SQL code.
    It works just fine for me :)
    Good luck.

  • Unix shell script run from pl/sql procedure

    Hi Guru
    I want to run unix shell script from pl/sql procedure. Actual I want to run it from developer 10g form.
    Please guide me in this regards
    Regards
    Jewel

    Look at the host or client_host builtins in the help

  • PL/SQL function - unix shell script

    Hello,
    I have an application that calls a unix shell script This unix shell script calls a oracle function in the PL/SQL package. For example,
    In package pkg_test, there is function f_test. This function returns pls_interger.
    How can I write a unix shell script to return the value from the oracle function, so that the application can get the value from the unix shell script?
    Many thanks.

    Thank you for your response.
    The Oracle functuion pkg_name.proc_name will return different values, 0, 1, 2, 3 in diffefrent conditions.
    The unix script, myscript.ksh calls pkg_name.proc_name.
    The other application will call myscript.ksh and this application will need to get the values 0, 1, 2, 3 from myscript.ksh.
    Can we make it without using the unix shelll function?
    Thanks.
    Edited by: slsam01 on Jun 2, 2009 9:21 PM

  • Sql script in UNIX

    When I run a sql script in unix using sqlplus command, the process halts at some point. No matter how long I wait, it does not finish (it does not bring the command prompt back). There are no problems in SQL*PLUS. This process usually takes about 30 mins when I run from SQL * PLUS. Any ideas why it hangs in UNIX?
    sqlplus -s userid @script
    Thanks

    Are you specifying a password ?
    Have you set the ORACLE_SID ?

  • Unix command into a pl/sql script

    Could you tell me how to run a unix command (cp, rm, mkdir....)
    into a pl/sql script ?

    sigh this is an old chestnut. it can only be done using a java stored procedure. the instructions for doing this can be found in old postings on this forum - use the Search facility. alternatively try the AskTom site, and Metalink posted a solution as well.
    rgds, APC

  • How to prepare for Converting UNIX shell scripts to PL/SQL

    Hi All
    I was said, that i may have to convert a lot of unix shell script to PL/SQL, what are the concepts i need to know to do it efficently,
    what are the options PL/SQL is having to best do that.
    I know the question is little unclear, but I too dont have much inputs about that i'm sorry for that, just its a question of how
    to prepare myself to do it the best way. What are the concepts i have to be familiar with.
    Many Thanks
    MJ

    Just how much work is involved, is hard to say. Many years ago I also wrote (more than once) a complete ETL system using a combination of shell scripts, SQL*Plus and PL/SQL.
    If the PL/SQL code is fairly clean, uses bind variables and not substitution variables, then it should be relatively easy to convert that PL/SQL code in the script to a formal stored procedure in the database.
    There is however bits and pieces that will be difficult to move into the PL/SQL layer as it requires new software - like for example FTP'ing a file from the production server to the ETL server. This can be done using external o/s calls from within PL/SQL. Or, you can install a FTP API library in PL/SQL and FTP that file directly into a CLOB and parse and process the CLOB.
    Think of Oracle as an o/s in its own right. In Oracle we have a mail client, a web browser, IPC methods like pipes and messages queues, cron, file systems, web servers and services, etc. And PL/SQL is the "shell scripting" (times a thousand) language of this Oracle o/s .
    In some cases you will find it fairly easy to map a Unix o/s feature or command to one in Oracle. For example, a Unix wget to fetch a HTML CSV file can easily be replaced in Oracle using a UTL_HTTP call.
    On the other hand, techniques used in Unix like creating a pipe to process data, grep for certain stuff and awk certain tokens for sed to process further... in Oracle this will look and work a lot different and use SQL.

  • Unix Shell Script -- ORA-00905 error in pl/sql

    Below is my unix shell script .... in which i am trying to caluclate difference between time stamps ..... i am getting a severe error when i run --- ORA-00905: missing keyword ( included it bottom of this post )
    please look into this and let me know where to correct ....
    much appreciated in adv
    ~~~~~~~~~~~~~~~~~~~~~START of Script~~~~~~~~~~~~~~~~~~~~
    #!/bin/ksh
    export readTime checkTime timeDiff
    # Get initial Time
    readTime=`sqlplus -s scott/tiger@database <<EOF
    whenever sqlerror exit 1
    set escape off
    set head off
    set verify off
    select SYSTIMESTAMP from dual;
    EOF
    `
    echo "readTime value is : $readTime"
    # Get end of time
    checkTime=`sqlplus -s scott/tiger@database <<EOF
    whenever sqlerror exit 1
    set escape off
    set head off
    set verify off
    select SYSTIMESTAMP from dual;
    EOF
    `
    echo "value of checkTime : $checkTime"
    # calculate time diff
    timeDiff=`sqlplus -s scott/tiger@database <<EOF
    whenever sqlerror exit 1
    set escape off
    set head off
    set verify off
    select CAST(TO_DATE('$time2','''YYYY\/MM\/DD:HH24:MI:SS'''))-CAST(TO_DATE('$VAR1','YYYY-MM-DD:HH24:MI:SS')) from dual;
    EOF
    `
    echo "value of timeDiff : $timeDiff"
    ~~~~~~~~~~~~~~~~~OUTPUT here ~~~~~~~~~~~~~~~~~~~~~~~
    readTime value is :
    02-DEC-05 12.07.53.779328 AM -06:00
    value of checkTime :
    02-DEC-05 12.07.54.013613 AM -06:00
    value of timeDiff : 02-DEC-05 12.07.54.013613 AM -06:00','''YYYY\/MM\/DD:HH24:MI:SS'''))-CAST(TO_DATE('
    ERROR at line 2:
    ORA-00905: missing keyword

    You didn't specify if you want a total time for a portion of a shell script, or the whole script in general. If you only want to know the time of the whole shell script, just reference the linux/unix built-in variable ${SECONDS}. This variable is reset for each PID.
    I usually add these lines to the bottom of long running shell scripts (just before an exit code):
    ~~~~~~~~~~~~~~~~~~~~~~~~~
    ((TIME = ${SECONDS} / 60))
    echo "Script ran for ${TIME} minutes. (${SECONDS} seconds total.)
    ~~~~~~~~~~~~~~~~~~~~~~~~~
    Like I said, ${SECONDS} starts ticking from 0 when you start the script, so no need to export the variable, just reference it. The nice part is that you don't have to bother getting into sqlplus and hit the database.

  • How can i call a Stored Procedure procedure from Unix shell script

    Hi All,
    I want to call a Strored PL-SQL Procedure through Unix shell script.
    Can any body help me with this.
    Regards,
    Saurabh

    I prefer a seperate script like the other poster mentioned. However, most shells can use a 'here' document as well ...
    sqlplus uid/pwd <<END
    exec myproc
    exit
    ENDRichard

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

  • 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

  • SQL script based on hostname and database name?

    I am trying to write a script that I can run on several unix servers and databases that will do different sql statements based on which server and database it is being run in.
    Something like:
    if hostname = 'A' and database name = 'D' then do this
    else if hostname = 'B' and database name = 'F' then do that
    I have tried many diifferent combinations of shell scripts and sql scripts but can't seem to get anything that works.
    Can someone help me out? Thanks.

    Since you are already able to get he db and host info, you are well on your way to branching based on that information. All you need is the basic framework:
    declare
      db VARCHAR2(30);
      host VARCHAR2(30);
      sqlcmd VARCHAR2(4000);
    begin
      select sys_context('userenv','host') host
           , sys_context('userenv','db_name') db_name
        into host
           , db
        from dual;
      case
        when db = 'XE' and host = 'mypc' then
          sqlcmd := q'[local_package.do_something('parm1', :db, :host)]';
          execute IMMEDIATE sqlcmd USING db, host;
        when db = 'DEV' and host in ('serv1','serv2') then
          sqlcmd := q'[different_packge.do_something('parm1', :db, :host)]';
          execute IMMEDIATE sqlcmd USING db, host;
        else
          dbms_output.put_line('unrecognized db/host combination: '||db||', '||host);
      end case;
    end;
    /In this example I've used dynamic SQL since not all instances are guaranteed to have any or all of the package procedures referenced in the dynamic sql. With out the dynamic sql, you would get errors and be unable to run the script on any instance lacking one or more of the reference package procedures..

  • Sending email attachments using unix shell script

    hi
    I want to send report generated my spooled file as attachment using unix shell script.
    Can somebody help me out ?
    many thanks

    thanks a tonn it worked.
    but i have another issue is it possible to add names in CC also ?
    Also here is my code which spools the output of SP to a txt file. the File name is generated dynamically.
    as shown below:
    I need to send this generated file as attachement.
    how do I do this? Here the shell script
    =========================================================
    #!/bin/sh
    ORA_USER=scott
    ORA_PWD=tiger
    #Get the input parameter
    if [ ! "$1" ]; then
    STR="NULL"
    else
    STR="'"$1"'"
    fi
    #echo "exec pkg1($STR);"
    #Connecting to oracle
    sqlplus -s <<EOF
    $ORA_USER/$[email protected]
    ---sql plus enviornment settings
    set linesize 160
    set pagesize 60
    set serveroutput on size 1000000 for wra
    set feedback off
    set termout off
    column dcol new_value mydate noprint
    select to_char(sysdate,'YYYYMMDDHH24MISS') dcol from dual;
    spool &mydate.report.txt
    exec pkg1($STR);
    spool off
    EOF
    exit
    =========================================================
    the file name will take sysdate as name so that every time a new file will be generated.
    this file I need to send as attachment.
    null

  • Calling stored procedure from unix shell script

    Hello,
    I am facing a problem while calling a stored procedure from UNIX shell script. I want to return a output variable from the stored procedure to the UNIX environment.
    Here is the code-
    #!/bin/sh
    OUTPUT=`sqlplus cmag/magnum@dw <<ENDOFSQL
    set serveroutput on;
    var prd_out varchar2(100);
    exec create_pm_window(:prd_out);
    exit;
    ENDOFSQL`
    echo " output is - $OUTPUT"
    The problem is :prd_out is not getting copied to shell variable OUTPUT.
    I have a dbms_output.put_line in the stored proc create_pm_window and I can see that prd_out is getting populated.
    Any help is really appreciated.
    Thanks'
    Rakhee

    First step :
    make sure the PL/SQL works as expected.
    Does the following display the expected output executed from SQL*Plus ?
    set serverout on
    declare
    prd_out varchar2(100);
    begin
    create_pm_window(prd_out);
    dbms_output.put_line('output is '||prd_out);
    end;
    I don't have your procedure, but using a dummy procedure like :
    Scott@my10g SQL>create procedure foo(p_out in out varchar2)   
      2  is
      3  begin
      4  select 'Hello '||instance_name into p_out from v$instance;
      5  end;
      6  /
    Procedure created. and a toto.sh script as :OUTPUT=`sqlplus -s scott/tiger <<EOF
    set pages 0 lines 120 trimout on trimspool on tab off echo off verify off feed off serverout on
    var mavar varchar2(100);
    exec foo(:mavar);
    print mavar;
    exit;
    EOF`
    echo "OUT = ${OUTPUT}"
    exitIt works fine :[oracle@Nicosa-oel ~]$ ./toto.sh
    OUT = Hello my10g

Maybe you are looking for