Sql Query in Unix script

Hi,
on 10G R2, on AIX 6.1,
in a shell script I want to do :
sqlplus user/password@mydb
select * from mytable.How to do that ?
Thank you.

Although you have got your answer, still I am posting my solution
sqlplus /nolog <<EOX
connect username/password@dbname
select * from blah;
EOX
If you do "sqlplus username/password@dbname" on command line, other users can see the password in "ps" command, which is violating security.
Cheers

Similar Messages

  • How can I pass value from sql query to unix script

    I am new to oracle/unix.
    I want to write a simple script to find max date from a table and then pass date into a variable in a korn shell script.
    sql is select max(date) from table;
    how can I pass that value in unix shell as a variable. Thanks

    I use to code like this.
    Enjoy Scripting.
    cmd.sql
    select sysdate from dual;
    exit
    db.sh
    #! /usr/bin/ksh
    . ~oracle/.orapaths
    dbdate=$(sqlplus -S user/pwd@servicename @cmd.sql)
    echo $dbdate
    Run shell scripts
    ./db.sh
    SYSDATE --------- 19-JAN-07

  • How to pass a result of SQL query to shell script variable

    Hi all,
    I am trying to pass the result of a simple SQL query that only returns a single row into the shell script variable ( This particular SQL is being executed from inside the same shell script).
    I want to use this value of the variable again in the same shell scirpt by opening another SQL plus session.
    I just want to have some values before hand so that I dont have to do multiple joins in the actual SQL to process data.

    Here an example :
    SQL> select empno,ename,deptno from emp;
         EMPNO ENAME          DEPTNO
          7369 SMITH              20
          7499 ALLEN              30
          7521 WARD               30
          7566 JONES              20
          7654 MARTIN             30
          7698 BLAKE              30
          7782 CLARK              10
          7788 SCOTT              20
          7839 KING               10
          7844 TURNER             30
          7876 ADAMS              20
          7900 JAMES              30
          7902 FORD               20
          7934 MILLER             10
    14 rows selected.
    SQL> select * from dept;
        DEPTNO DNAME          LOC
            10 ACCOUNTING     NEW YORK
            20 RESEARCH       DALLAS
            30 SALES          CHICAGO
            40 OPERATIONS     BOSTON
    SQL> exit
    Disconnected from Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - Production
    With the Partitioning, OLAP and Data Mining options
    $ cat my_shell.sh
    ### First query #####
    ENAME_DEPTNO=`sqlplus -s scott/tiger << EOF
    set pages 0
    select ename,deptno from emp where empno=$1;
    exit
    EOF`
    ENAME=`echo $ENAME_DEPTNO | awk '{print $1}'`
    DEPTNO=`echo $ENAME_DEPTNO | awk '{print $2}'`
    echo "Ename         = "$ENAME
    echo "Dept          = "$DEPTNO
    ### Second query #####
    DNAME_LOC=`sqlplus -s scott/tiger << EOF
    set pages 0
    select dname,loc from dept where deptno=$DEPTNO;
    exit
    EOF`
    DNAME=`echo $DNAME_LOC | awk '{print $1}'`
    LOC=`echo $DNAME_LOC | awk '{print $2}'`
    echo "Dept Name     = "$DNAME
    echo "Dept Location = "$LOC
    $ ./my_shell.sh 7902
    Ename         = FORD
    Dept          = 20
    Dept Name     = RESEARCH
    Dept Location = DALLAS
    $                                                                           

  • SQL Query in Shell script

    Hi everyone,
    I am facing a difficulty in writing a query for a table REF_PRODUCT having some columns like OFFER, PROVIDERID.
    The problem statement is
    if the OFFER not in ('A','B','C') then x='D'
    if x is empty then
    if providerid in (some values) then x='A'
    else if providerid in (some other values) then x='B'
    else x='C'
    where x is a variable in shell script.
    I want to execute the above in shell script. how to manage this?
    Please help..
    Regards
    Abhi

    user8744860 wrote:
    I am facing a difficulty . . . Etc . . .
    I want to execute the above in shell script. how to manage this?
    Please help..
    1) What you posted is not a shell script.
    2) In order for us to help you with your question, you need to post a working test case: create table and insert statements
    as well as the expected result from that data. Provide also an explanation of the rules that lead to this result.
    3) Also provide any code you have written.
    :p

  • Unix script output sql result to terminal

    Hi,
    I run the script below within a unix script. the query runs but only outputs the first line. I need the whole results output to the terminal.. please let me know if I am doing something wrong. thanks
    ORACLE_SID=orcl
    export ORACLE_SID
    SHELL=/bin/sh
    db="username/password"
    sqlplus -s $db <<xxx
    set serveroutput on
    define yy=100
    whenever sqlerror exit yy
    begin
    declare
    Dyn_table_name VARCHAR2(100);
    Dyn_query_string VARCHAR2(4000);
    Type csr_dyn IS REF CURSOR;
    csr_dyn1 csr_dyn;
    col1 varchar2(200);
    col2 varchar2(200);
    col3 varchar2(200);
    col4 varchar2(200);
    col5 varchar2(200);
    begin
    Dyn_table_name :='''my_table''';
    Dyn_query_string :='SELECT b.session_id ,s.serial#,NVL(b.oracle_username,''(oracle)'') AS username,'
    ||'a.object_name,b.os_user_name FROM dba_objects a,v\$locked_object b,v\$session s'
    ||' WHERE a.object_id =Upper(b.object_id)and b.session_id=s.sid and a.object_name='||Dyn_table_name;
    /*dbms_output.put_line(Dyn_query_string);*/
    dbms_output.put_line('SID'||' '|| 'serial#' || ' '||'USERNAME'||' '||'OBJECT_NAME'||' '||'OS_USER_NAME');
    dbms_output.put_line('------------------------------------------------------------------------------------');
    OPEN csr_dyn1 FOR dyn_query_string;
    LOOP
    FETCH csr_dyn1 INTO col1,col2,col3,col4,col5;
    EXIT WHEN csr_dyn1%NOTFOUND;
    dbms_output.put_line(col1||' '|| col2||' '|| col3 || ' ' || col4 ||' '|| col5);
    END LOOP;
    EXCEPTION WHEN OTHERS THEN
    dbms_output.put_line(to_char(sqlcode)|| ' '|| sqlerrm);
    end;
    end;
    set serveroutput off
    exit
    xxx

    Sorry all your suggestion did not work ( the log file had this error message
    Usage 1: sqlplus -H | -V
    -H Displays the SQL*Plus version and the
    usage help.
    -V Displays the SQL*Plus version.
    Usage 2: sqlplus [ [<option>] [<logon>] [<start>] ]
    <option> is: [-C <version>] [-L] [-M "<options>"] [-R <level>] [-S]
    ... I know its possible to login into sqlplus and run the querry, but I want it as a script which would output this kind of result to the screen
    SESSION_ID SERIAL# USERNAME OBJECT_NAME      OS_USER_NAME
    251     30330     PRD my table     oracle
    335     11624     PRD     my table     oracle
    469     2592     PRD     my table     oracle
    849     8619     PRD     my table     oracle
    934     40211     PRD     my table     oracle
    955     15043     PRD     my table     oracle
    is it possible or am I asking for the impossible...!!! I appreciate your suggestion... you can alter the script I put up and paste the correction so that I can see cleary how you made it work for you.

  • Starting and stopping an SQL query from within a Shell script

    DB version:10gR2
    OS Version:AIX
    We have a C++ application called WpnCreate.cpp, which is causing some locking problems.
    So, we have decided to capture(using SPOOL) the locking info(session info, blocking program,..etc) using an SQL query.
    WpnCreate.cpp program is initiated by a shell script. So we need this SQL query(.sql) to start firing just before WpnCreate.cpp is called and when WpnCreate.cpp has finished executing, we need the SQL query execution to stop.
    But how do i stop the sql query execution? Should i capture the session id and serial# of this session and use kill -9 at the end of the shell script?
    Flow of the Shell script should be like this
    Step1. Start firing the SQL query which captures the locking info and SPOOL them to a file
    Step2. Execute WpnCreate.cpp program
    Step3. Stop the firing of SQL query once WpnCreate.cpp has finished executing ( i don't know how)How will i go about achieving this?

    How can you run your step 2 untill & unless your step 1 gets over. You can run in background but then it will not capture the correct information.
    I think you need to run your step 1 after step 2 , then only you will be able to capture the information.
    You can run your C++ program in background and can wait for some time using sleep command and then run the query to check the locking information.

  • Looking for an SQL query to retreive callvariables + ECC from a RUN SCRIPT RESULT (Translation to VRU)

    Hi Team,
    I am looking for an SQL query to check the data (ECC + CallVariable) received following a RUN SCRIPT RESULT when requesting an external VRU with a Translation Route to VRU with a "Run External Script".
    I believe the data are parsed between the Termination Call Detail + Termination Call Variable .
    If you already have such an SQL query I would very much appreciate to have it.
    Thank you and Regards
    Nick

    Omar,
    with all due respect, shortening a one day's interval might not be an option for a historical report ;-)
    I would recommend to take a look the following SQL query:
    DECLARE @dateFrom DATETIME, @dateTo DATETIME
    SET @dateFrom = '2014-01-24 00:00:00'
    SET @dateTo   = '2014-01-25 00:00:00'
    SELECT
    tcv.DateTime,
    tcd.RecoveryKey,
    tcd.RouterCallKeyDay,
    tcd.RouterCallKey,
    ecv.EnterpriseName AS [ECVEnterpriseName],
    tcv.ArrayIndex,
    tcv.ECCValue
    FROM Termination_Call_Variable tcv
    JOIN
    (SELECT RouterCallKeyDay,RouterCallKey,RecoveryKey FROM Termination_Call_Detail WHERE DateTime > @dateFrom AND DateTime < @dateTo) tcd
    ON tcv.TCDRecoveryKey = tcd.RecoveryKey
    LEFT OUTER JOIN Expanded_Call_Variable ecv ON tcv.ExpandedCallVariableID = ecv.ExpandedCallVariableID
    WHERE tcv.DateTime > @dateFrom AND tcv.DateTime < @dateTo
    With variables, you can parametrize your code (for instance, you could write SET @dateFrom = ? and let the calling application fill in the datetime value in for you).
    Plus joining two large tables with all rows like you did (TCD-TCV) is never a good option.
    Another aspect to consider: all ECC's are actually arrays (always), so it's not good to leave out the index value (tcv.ArrayIndex).
    G.

  • How ro run unix script freom pl/sql - dbms_scheduler 11.2.0.3

    Hi,
    Using 11.2.0.3 and have a unix script which works fine.
    Want to run this unix script every time a piece of pl/sql runs
    have put below in but doesn't actually run it.
    How can we achieve this?
    Many Thanks
    idea is that file we create locqally on server is copied to another via the unix script caled form pl/sql
    DBMS_SCHEDULER.create_program (
       program_name => 'test_executable_prog',
       program_type => 'EXECUTABLE',
       program_action => '/oracle/jm/data/dataout/copy_tcfile',
       number_of_arguments => 0,
       enabled => TRUE,
       comments => 'CREATE_PROGRAM test using a schell script.');Tried below but no joy
    -- Shell Script (OS executable file).
    /*DBMS_SCHEDULER.drop_program(program_name => 'por_copy_files');
    DBMS_SCHEDULER.create_program (
       program_name => 'por_copy_files',
       program_type => 'EXECUTABLE',
       program_action => ' /oracle/jm/data/dataout/copy_tcfile',
       number_of_arguments => 0,
       enabled => TRUE,
       comments => 'CREATE_PROGRAM test using a schell script.');
    DBMS_SCHEDULER.create_job (
        job_name        => 'por_copy_files_job',
        program_name    => 'por_copy_files',
        start_date      => null,--SYSTIMESTAMP,
        repeat_interval => null,--'freq=hourly; byminute=0',
        end_date        => NULL,
        enabled         => TRUE,
        comments        => 'Job defined by existing program and inline schedule.');Edited by: user5716448 on 03-Oct-2012 08:35
    Getting message when look in all_scheduler_job_run_details
    ORA-27369: job of type EXECUTABLE failed with exit code: No such file or directory
    even thoug hfile exists
    Edited by: user5716448 on 03-Oct-2012 08:50

    When run for unix command line which o.k
    get
    AUTHSTATE=files
    A__z=! LOGNAME
    COLUMNS=132
    EDITOR=vi
    ENV=/home/oracle/.kshrc
    HOME=/home/oracle
    LANG=en_US
    LC__FASTMSG=true
    LOCPATH=/usr/lib/nls/loc
    LOGIN=oracle
    LOGNAME=oracle
    MAIL=/usr/spool/mail/oracle
    MAILMSG=[YOU HAVE NEW MAIL]
    MAIL_HOST=prdikw01
    NLSPATH=/usr/lib/nls/msg/%L/%N:/usr/lib/nls/msg/%L/%N.cat
    ODMDIR=/etc/objrepos
    ORACLE_BASE=/oracle/app/oracle
    ORACLE_HOME=/oracle/app/oracle/product/11.2.0/dbhome_1
    ORACLE_SID=IKW
    ORACLE_TERM=vt100
    ORATAB_PATH=/etc
    PATH=/usr/bin:/etc:/usr/sbin:/usr/ucb:/usr/bin/X11:/sbin:/usr/java5/jre/bin:/usr/java5/bin:/usr/local/bin:/etc:/usr/sbin:/usr/ucb:/h
    ome/oracle/bin:/usr/bin/X11:/sbin:/oracle/app/oracle/product/11.2.0/dbhome_1/bin:/oracle/app/oracle/product/11.2.0/dbhome_1/OPatch
    PS1=[$ORACLE_SID]$PWD $
    PWD=/oracle/jm/data
    SHELL=/usr/bin/ksh
    TERM=xterm
    TMPDIR=/tmp
    TZ=GMT0BST,M3.5.0,M10.5.0
    USER=oracle
    _=/usr/bin/env
    dba=/home/oracle/dbaWhen run from pl/sql
    get
    ORA-27369: job of type EXECUTABLE failed with exit code: 255
    STANDARD_ERROR="execve: Exec format error"when try
    dbms_scheduler.create_job(
    job_name => 'POR_JOB',
    job_type => 'EXECUTABLE',
    job_action => '/oracle/jm/data/copy_tcfile',
    start_date => SYSTIMESTAMP,
    number_of_arguments=>0,
    enabled => true,
    auto_Drop => true,
    comments => 'Demo');Above code in pl/sql where create job and schedule job separately gives file not found message even though give full path

  • More on unix script from pl/sql

    Hi All,
    There was this discussion on starting unix scripts from within a pl/sql stored procedure started on August 31.
    All comments were targeted towards an oracle 8X solution.
    Does anyone have a solution for 7.3.4?
    Somebody mentioned something about using dbms_pipe package.
    So, just to rephrase the problem:
    - Need to execute any unix command/script from within a pl/sql block (stored procedure). Instance is oracle 7.3.4
    Thanks!
    Enrique

    Hi Juan,
    You can try this solution:
    enable in the the init file the parameter
    utl_file_dir="target_directory"In this way You permit the the DB to writing directly to the filesistem in the directory You specified.
    After restarting the istance You may write Your own code that, using the supplied package UTL_FILE, writes a file in that directory (es. my_script.sh)
    Then, instruct the cron daemon to execute every 1 minute this command.
    You may append to the script the self-destruction after the execution.
    I hope that this will help You.
    Max

  • Call a unix script from pl/sql package

    Hi,
    Using 11.2.0.3 on AIX.
    Is it possible to call unix script from pl/sql package?
    I am cretaing a file in a directory but would like this to automatically be written to an archive directory as well.
    Could either use 2 utl_file.put_lines to 2 separate directories or 1 utl_file and cal script to archive file in another directory.?
    Thoughts?
    Thanks

    user5716448 wrote:
    What am I doing wrong?think how file name will look like:
    SQL> select 'file_name' || to_char(sysdate,'DD/MM/YYYY HH24:MI:SS') from dual;
    'FILE_NAME'||TO_CHAR(SYSDATE
    file_name15/08/2012 11:47:51Will AIX swallow such name? Obviously not. And, unfortunately, UTL_FILE.FCOPY doesn't raise an error in such case. So use someting like:
    UTL_FILE.FCOPY ('SOURCE_DIR',v_FILE_NAME,'DEST_DIR',v_file_name||to_char(sysdate,'DD_MM_YYYY_HH24_MI_SS'));SY.

  • Unix script in Oracle Pl/sql

    I created a unix script which is automatically transfer the file from one instance to other .Now i want to call that script from pl/sql ,how can i do that
    Kindly give the suggestion

    Check the following link. It contains the steps to execute system commands from PL/SQL.
    http://www-rohan.sdsu.edu/doc/oracle/server803/A54642_01/ch8.htm

  • Basic SQL query scripts for SAP B1

    hi guys,
    do you have any documents, guides or reference links regarding basic SQL query scripts for SAP B1?
    thanks and have a nice day!
    blake p.

    Hi
    You can also check SBONotes.com.
    For sql understanding , you can search in websearch - tsql and it will pop up with informations you need.
    You can also refer to forum once you understand the basic techniques
    Hope this helps
    Bishal

  • How to check UNUSED ADMIN-SCRIPTS through SQL Query..??

    Can someone help me with the SQL query, which would give result of total unused ADMIN SCRIPTs for past few months?? (not the routing scripts)
    Thanks in advance for your help n concern..!!

    You can youse the below queries
    Step 1:
    Query to pull the used scripts between 17/12/2011 to 18/01/2012
    select MasterScriptID,EnterpriseName from Master_Script where MasterScriptID in (
    select MasterScriptID from Script where ScriptID in(
    select distinct(ScriptID) from Route_Call_Detail
    where DateTime between '2011-12-17 00:00:00' and '2012-01-18 23:59:59'))
    Step 2:
    Query to pull all the current configured Scripts 
    select MasterScriptID,EnterpriseName from Master_Script
    Step 3:
    Once we get both the data, we can use Excel’s VLOOKUP functionality to find the unused Scripts
    Regards,
    Senthil

  • Script task to convert output from a sql query into send mail task body formatting

    SSIS 2008R2 Version
    Code from script task
       Microsoft SQL Server Integration Services Script Task
       Write scripts using Microsoft Visual C# 2008.
       The ScriptMain is the entry point class of the script.
    using System;
    using System.Data;
    using Microsoft.SqlServer.Dts.Runtime;
    using System.Windows.Forms;
    namespace ST_29dd6843bd6c4aee9b1656c1bbf55ba8.csproj
        [System.AddIn.AddIn("ScriptMain", Version = "1.0", Publisher = "", Description = "")]
        public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
            #region VSTA generated code
            enum ScriptResults
                Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
                Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
            #endregion
            public void Main()
                Variables varCollection = null;
                string header = string.Empty;
                string message = string.Empty;
                Dts.VariableDispenser.LockForWrite("User::gsEmailMessage");
                Dts.VariableDispenser.LockForWrite("User::gsWebserviceName");
                Dts.VariableDispenser.LockForWrite("User::gsNoOfCallsInADay");
                Dts.VariableDispenser.LockForWrite("User::gsCalledBySystem");
                Dts.VariableDispenser.GetVariables(ref varCollection);
                //Set the header message for the query result
                if (varCollection["User::gsEmailMessage"].Value == string.Empty)
                    header = "Hi, Count is greater then 50 :\n\n";
                    //header = "Execute SQL task output sent using Send Email Task in SSIS:\n\n\n";
                    header += "----------------------------------------------------------------------------------------------------------------------" + "\n";
                    header += string.Format("{0}\t\t\t\t{1}\t\t{2}\n", "WebService Name", "No Of Calls In A Day", "Called By System");
                    header += "----------------------------------------------------------------------------------------------------------------------" + "\n";
                    varCollection["User::gsEmailMessage"].Value = header;
                //Format the query result with tab delimiters
                     message = String.Format("<HTML><BODY><P>{0}</P><P>{1}</P><P>{2}</P></BODY></HTML>",
                                            varCollection["User::gsWebserviceName"].Value,
                                            varCollection["User::gsNoOfCallsInADay"].Value,
                                            varCollection["User::gsCalledBySystem"].Value);
                varCollection["User::gsEmailMessage"].Value = varCollection["User::gsEmailMessage"].Value + message + "\n";
                Dts.TaskResult = (int)ScriptResults.Success;
    Above code will return data in below format and then i send this output in aemail using send mail task.
    Hi, count is greater then 50 :
    WebService Name                                                         
    No Of Calls In A Day                        Called By System
    WebServiceone                                                     1                             
    Internetbutiken
    WebServiceGetdetailstwo                                                  1                             
    Internetbutiken
    Servicenamethree                                                            2                             
    MOB
    As you can see above code is not in align as if we service name is shorter then 2nd column get disallign and its not look good.I need output should be like below.
    Hi, count is greater then 50 :
    WebService Name                                                         
    No Of Calls In A Day                        Called By System
    WebServiceone                                                              1                             
    Internetbutiken
    WebServiceGetdetailstwo                                              1                             
    Internetbutiken
    Servicenamethree                                                          2                             
    MOB
    Please suggest something...
    Thanks 
    SR_MCTS

    See code explained here
    http://microsoft-ssis.blogspot.in/2013/08/sending-mail-within-ssis-part-2-script.html
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs
    This will not help.As I am not creating smtp connectin ,send from ,send to in script task.I am just creating email body from sql output.

  • Unix Scripts and PL/SQL

    I want to run a UNIX script via PL/SQL. I want the script to be run with no assistance from an outside source. The script contains a 'ls'. Is this possible and if so, how.

    <BLOCKQUOTE><font size="1" face="Verdana, Arial, Helvetica">quote:</font><HR>Originally posted by Christopher Racicot ([email protected]):
    You can use an "external procedure", written in C, which then uses the C runtime library to access the UNIX shell. This features is
    also known as "callouts".
    We will likely add better native support
    in PL/SQL for various operating system
    activities in a future release.<HR></BLOCKQUOTE>
    Can you invoke Perl from within PLSQL?

Maybe you are looking for