Friday 24 June 2011

How to find out locking and blocking in sql server using t-sql?

SELECT  r.session_id,
            s.host_name,
            s.login_name,
            r.start_time,
            r.sql_handle,
            r.blocking_session_id,
            SUM(r.reads) AS totalReads,
            SUM(r.writes) AS totalWrites,
            SUM(r.cpu_time) AS totalCPU,
            SUM(tsu.user_objects_alloc_page_count + tsu.internal_objects_alloc_page_count) AS writes_in_tempdb
    FROM    sys.dm_exec_requests r
    JOIN    sys.dm_exec_sessions s ON s.session_id = r.session_id
    JOIN    sys.dm_db_task_space_usage tsu ON s.session_id = tsu.session_id and r.request_id = tsu.request_id
    WHERE   r.status IN ('running', 'runnable', 'suspended')
      and r.blocking_session_id <> 0
    GROUP BY    r.session_id,
                s.host_name,
                s.login_name,
                r.start_time,
                r.sql_handle,
                r.blocking_session_id

Monday 20 June 2011

CHECKLIST FOR SQL SERVER MIGRATION

Below is the checlist for Server Migration . We migrated a from HP server to Dell Server So this was the process we followed.
-------------------------------------------
** CHECKLIST  FOR  SERVER  MIGRATION **
-------------------------------------------
1. Check the SQL Server Edition on "Source" and "Destination" machine.
2. Check the service pack on "Source" and "Destination" machine.
3. Document the existing SQL Server settings so that it should match the same (collation,version,...)
4. Take Full backups of all System and Application databases on "Source" machine.
5. Script all logins on "Source" and "Destination" machine.
6. Script all jobs on "Source" and "Destination" machine.
7. List out all Maintenance Plans and their schedules.
8. List out all Linked server(s) currently being used.


---------------------
Migration Process :
---------------------
1. Migrate logins (Please use the script - http://support.microsoft.com/kb/246133 to transfer the logins to the newly built server. In this way you dont have to fix any orphaned users)
2. Restore all Application Databases
3. Fix the Orphan Users, if required.
4. Create the jobs on the destination server, which you have scripted before starting the migration activity.
5. Create maintenance plans on the destination server.
6. Create Linked Servers on the destination server.
7. Perform checkdb on all databases.
8. Rebuild indexes on all databases.
9. Update the statistics on all databases.
10. Move all the DTS packages.
11. Point the application to new server
12. Testing ....


---------------------
NOTES:
---------------------
1. After you rename the physical server and startup the sql server, if run @@SERVERNAME u would find still the old server name getting reflected. You woud need to run the sp_dropserver and the sp_addserver to reflect the new name.
A simpler way would be once ur old machine is down, just restore the backup of the master db of the old machine. This way u avoid scripting logins, server level settings, linked servers etc. but a word of caution, the location of ur db files (msdb and other user db's) should be identical else sql server would refuse to startup.

2. Check the connectivity through the client tool (sql server EM or Query Analyzer) from another machine or a client machine. If there are connectivity probs u would need to troubleshoot further.


3. A good prac would be to keep ur mdf, ldf and tempdb files in different physical drives to isolate disk/IO. Also choose the approriate raid levels for the storage subsystem. Put a cap on max memory. Set a intial size for the temp db and create 2 temp data files to take adv of parallel processing of CPU. Set a intial size to all user db's and an auto grow option in either % or MB's.

4. Keep tempdb in diff physical disk with raid 10 preferrably.


------------------------------------------
 

Commonly used scripts for all the Oracle DBA

Commonly used Scripps for all the Oracle applications Database Administrators/Sysadmin:

Canceling Concurrent program from backend:

1) Get the SID for the given request ID using below script

select
           req.request_id
,      req.oracle_process_id
,      req.os_process_id
,      ses.sid
,      ses.serial#
,      ses.program
,      req.logfile_name log
,      req.outfile_name out
from  v$process pid
,     v$session ses
,     apps.FND_CONCURRENT_REQUESTS req
where req.request_id = &request_id
and   req.oracle_process_id = pid.spid(+)
and   pid.addr = ses.paddr(+)

2) Take the SID and cancel the program using below command

Alter system kill session ‘sid, serial#’

3) If it is a request set and you can not able to cancel from front-end then cancel the program using below command:

Update apps.fnd_concurrent_requests
Set phase_code='C',status_code='D' where request_id='12345678'

4) Even after canceling the SID still it is having Oracle process id then take the Oracle Process id from the script 1 and go to UNIX session and connect as applmgr and kill that particular session

Kill -9 Oracle_process_id



Script to find out lock for any session:

select
   substr(to_char(l.session_id)||','||to_char(s.serial#),1,12) sid_ser,
   substr(l.os_user_name||'/'||l.oracle_username,1,12) username,
   l.process,
   s.sid,
   p.spid,
   substr(o.owner||'.'||o.object_name,1,35) owner_object,
   decode(l.locked_mode,
            1,'No Lock',
            2,'Row Share',
            3,'Row Exclusive',
            4,'Share',
            5,'Share Row Excl',
            6,'Exclusive',null) locked_mode,
   substr(s.status,1,8) status
from
   v$locked_object l,
   all_objects     o,
   v$session       s,
   v$process       p
where
   l.object_id = o.object_id
and l.session_id = s.sid
and s.paddr      = p.addr
and s.status != 'KILLED';




Script to find out all the running sessions


select a.request_id                                                             "rqst_id"
      ,a.program_application_id                                                 "pgm_appl_id"
      ,a.concurrent_program_id                                                  "conc_pgm_id"
      ,a.status_code||decode(a.resubmit_interval, null, null, '*')              "stat_cd"
      ,b.os_process_id                                                          "os_pid"
      ,v.spid                                                                   "vspid"
      ,v.sid                                                                    "vsid"
      ,v.serial#                                                                "vserial#"
      ,a.priority                                                               "pri"
      ,substr(d.concurrent_queue_name,1,3)                                      "que"
      ,(nvl(actual_completion_date,sysdate)-actual_start_date)*1440             "time"
      ,round(f.time_avg,2)                                                      "avgtime"
      ,decode(sign(a.requested_start_date - a.request_date),1,
              round(((sysdate-requested_start_date) * 1440),0),
              round(((sysdate-request_date) * 1440),0))                         "walltime"
      ,e.user_name                                                              "usr"
      ,c.concurrent_program_name||' - '||rtrim(ct.user_concurrent_program_name) program"
  from APPLSYS.fnd_concurrent_requests     a
      ,APPLSYS.fnd_concurrent_processes    b
      ,APPLSYS.fnd_concurrent_programs     c
      ,APPLSYS.fnd_concurrent_programs_tl  ct
      ,APPLSYS.fnd_concurrent_queues       d
      ,APPLSYS.fnd_user                    e
      ,APPLSYS.fcr_stats                   f
      ,(select s.sid, s.serial#, p.spid from v$session s, v$process p where s.paddr = p.addr) v
 where a.controlling_manager = b.concurrent_process_id
   and a.concurrent_program_id = c.concurrent_program_id
   and a.concurrent_program_id = f.concurrent_program_id(+)
  and a.program_application_id = f.application_id(+)
   and a.program_application_id = c.application_id
   and a.concurrent_program_id = ct.concurrent_program_id
   and a.program_application_id = ct.application_id
   and b.concurrent_queue_id = d.concurrent_queue_id
   and ct.language = 'US'
  and a.requested_by = e.user_id
   and a.phase_code in ('R','T')
   and a.oracle_process_id=v.spid(+)
   order by 11 asc




Script to find out the concurrent manager for a given request

Select /*+ RULE */
       decode(F.node_name,'hp14fat', 'hp14fat:rptd *', 'hp05fat', 'hp05fat:prod', '' ) Node,
       substr(User_Concurrent_Queue_Name,1,20) Manager,
       Request_Id Request, User_name,
       Fpro.OS_PROCESS_ID OSproc,
       substr(user_Concurrent_Program_Name,1,30) Program,
       To_Char(Actual_Start_Date, 'RR-MM-DD HH24:MI') Started
  from apps.Fnd_Concurrent_Queues_tl Fcq, apps.Fnd_Concurrent_Requests Fcr,
       apps.Fnd_Concurrent_Programs_tl Fcp,
       apps.Fnd_User Fu, apps.Fnd_Concurrent_Processes Fpro,
       apps.fnd_concurrent_queues f
 where
       Phase_Code = 'R' And
       Status_Code <> 'W' And
       Fcr.Controlling_Manager = Concurrent_Process_Id       And
      (Fcq.Concurrent_Queue_Id = Fpro.Concurrent_Queue_Id    And
       Fcq.Application_Id      = Fpro.Queue_Application_Id ) And
      (Fcr.Concurrent_Program_Id = Fcp.Concurrent_Program_Id And
       Fcr.Program_Application_Id = Fcp.Application_Id )     And
       F.concurrent_queue_id = Fcq.concurrent_queue_id       And
       Fcr.Requested_By = User_Id                          
       order by Started,2




Script to find locks (wait)

set linesize 150
set pagesize 1000
set feedback off
set verify off
col sidstatus form a7 head "Status"
column username format a8
column osuser format a8
column machine format a12
column terminal format a8
column sid format 99999
column serial# format 999999
column logon_time format a14

column program form a52

rem WHENEVER SQLERROR EXIT FAILURE ROLLBACK;

prompt
prompt
prompt Waiting vs Holding ...
prompt ======================

col LOCK_TYPE form a12
col MODE_HELD form a20
col MODE_REQUESTED form a20
col LOCK_ID1 form a10
col LOCK_ID2 form a10

REM SID output in special format for URL handling
col waiting_sid format a11 head "Waiting"
col holding_sid format a11 head "Holding"

Select
  ':SID:' || WAITING_SESSION || ':' waiting_sid,
  ':SID:' || HOLDING_SESSION || ':' holding_sid,
  LOCK_TYPE, MODE_HELD, MODE_REQUESTED, LOCK_ID1, LOCK_ID2
From SYS.DBA_WAITERS
;

set termout off

define hsid1 = 0
define hsid2 = 0
define hsid3 = 0
define hsid4 = 0
col hsid1 new_val hsid1
col hsid2 new_val hsid2
col hsid3 new_val hsid3
col hsid4 new_val hsid4

select 0 hsid1, 0 hsid2, 0 hsid3, 0 hsid4 from dual;

REM Below - get maximum of 4 holding sessions ids

REM Select max(decode(mod(ROWNUM,5),1,HOLDING_SESSION,0)) hsid1,
REM        max(decode(mod(ROWNUM,5),2,HOLDING_SESSION,0)) hsid2,
REM        max(decode(mod(ROWNUM,5),3,HOLDING_SESSION,0)) hsid3,
REM        max(decode(mod(ROWNUM,5),4,HOLDING_SESSION,0)) hsid4
REM From SYS.DBA_WAITERS
REM Where ROWNUM < 5
REM Group by ROWNUM - mod(ROWNUM,5)
REM ;

Select max(decode(mod(rownum,5),1,SID,0)) hsid1,
       max(decode(mod(rownum,5),2,SID,0)) hsid2,
       max(decode(mod(rownum,5),3,SID,0)) hsid3,
       max(decode(mod(rownum,5),4,SID,0)) hsid4
From v$lock
Where block != 0
And rownum < 5
Group by rownum - mod(rownum,5)
;

variable hsid1 number;
variable hsid2 number;
variable hsid3 number;
variable hsid4 number;
begin
  :hsid1 := &hsid1;
  :hsid2 := &hsid2;
  :hsid3 := &hsid3;
  :hsid4 := &hsid4;
end;
/

set termout on

prompt
prompt
prompt Waiting ...
prompt ===========

Select decode(S.LOCKWAIT, NULL, 'Holding', 'Waiting') sidstatus,
       S.SID, S.SERIAL#,
       S.PROCESS, S.USERNAME, S.OSUSER,
       to_char(S.LOGON_TIME, 'mm/dd hh24:mi:ss') "LOGON_TIME",
       S.MACHINE, S.TERMINAL, S.PROGRAM
From V$SESSION S
Where S.LOCKWAIT IS NOT NULL
;

prompt
prompt
prompt Holding ...
prompt ===========

Select decode(S.LOCKWAIT, NULL, 'Holding', 'Waiting') sidstatus,
       S.SID, S.SERIAL#,
       S.PROCESS, S.USERNAME, S.OSUSER,
       to_char(S.LOGON_TIME, 'mm/dd hh24:mi:ss') "LOGON_TIME",
       S.MACHINE, S.TERMINAL, S.PROGRAM
From V$SESSION S
Where S.SID in (:hsid1, :hsid2, :hsid3, :hsid4)
;

clear breaks

prompt
prompt
prompt Session Wait Info
prompt =================

col STATE form a20
col EVENT form a40
col P1TEXT form a30
col Minutes_in_Wait form 999999

Select decode(S.LOCKWAIT, NULL, 'Holding', 'Waiting') sidstatus,
       W.SID, SECONDS_IN_WAIT/60 "Minutes_in_Wait", STATE,
       EVENT, P1TEXT
From V$SESSION_WAIT W, V$SESSION S
Where (S.LOCKWAIT IS NOT NULL Or S.SID in (:hsid1, :hsid2, :hsid3, :hsid4))
And W.SID = S.SID




Script to find out the users having System Administrator responsibility:

select a.responsibility_name, c.user_name, c.description
from apps.fnd_responsibility_vl a,apps.fnd_user_resp_groups b, apps.fnd_user c
where a.responsibility_id=b.responsibility_id and
a.application_id=b.responsibility_application_id and
b.user_id=c.user_id and
a.responsibility_id=20420 and
(b.end_date IS NULL or b.end_date > SYSDATE) and
(c.end_date IS NULL or c.end_date > SYSDATE)





Compiling Invalid objects using below script:

DECLARE
 obj_number number := 0;
 cursor C1 is select o.obj#, 
           'ALTER ' || decode (o.type#,
                               4, 'VIEW ',
                               7, 'PROCEDURE ',
                               8, 'FUNCTION ',
                               9, 'PACKAGE ',
                               11, 'PACKAGE ',
                               12, 'TRIGGER ',
                               13, 'TYPE ',
                               14, 'TYPE ',
                               ' ') ||
            u.name || '.' || o.name || ' COMPILE ' ||
                       decode (o.type#,
                               9, 'SPECIFICATION',
                               11, 'BODY',
                               13, 'SPECIFICATION',
                               14, 'BODY',
                               ' ')
           from obj$ o, user$ u
           where o.obj# > obj_number and 
           u.user# = o.owner# and o.remoteowner is NULL and
           o.status in (4,5,6) and o.type# in (4, 7, 8, 9, 11, 12, 13, 14)
           order by o.obj#;
  DDL_CURSOR integer;
  ddl_statement varchar2(200);
  iterations number;
  loop_count number;
  my_err     number;
  validate   number;
BEGIN
 loop_count := 0;
 -- To make sure we eventually stop, pick a max number of iterations
 select count(*) into iterations from obj$ where remoteowner is NULL and
           status in (4,5,6) and type# in (4, 7, 8, 9, 11, 12, 13, 14); 
 DDL_CURSOR := dbms_sql.open_cursor;
 OPEN C1;
 LOOP
   BEGIN
     FETCH C1 INTO obj_number, ddl_statement;
     EXIT WHEN C1%NOTFOUND OR loop_count > iterations;
   EXCEPTION
    WHEN OTHERS THEN
      my_err := SQLCODE;
      IF my_err = -1555 THEN -- snapshot too old, re-execute fetch query
       CLOSE C1;
       -- Here is why C1 orders by obj#.  When we restart the query, we 
       -- will only find object with obj# greater than the last one tried.
       -- This keeps us from re-trying objects that failed.
       OPEN  C1;
       GOTO continue;
      ELSE
       RAISE;
      END IF;
   END;
   -- Check to see if already validated as a result of earlier compiles
   select count(*) into validate from obj$ where obj# = obj_number and
    status in (4,5,6);
   IF validate = 1 THEN
     BEGIN
       -- Issue the Alter Statement  (Parse implicitly executes DDLs)
       dbms_sql.parse(DDL_CURSOR, ddl_statement, dbms_sql.native);
     EXCEPTION
       WHEN OTHERS THEN
        null; -- ignore, and proceed.
     END;
   END IF;
 <<continue>>
   loop_count := loop_count + 1;
 END LOOP;
 dbms_sql.close_cursor(DDL_CURSOR);
 CLOSE C1;
END;
/


Unix for Oracle Database Administrators

Unix for Oracle Database Administrators







The Article is a quick reference describing, how to create complex one-line Unix commands in addition to some most often used Unix commands used by Oracle database administrators.

Building Unix Commands


One of the most confounding things for the Unix neophyte is being confronted with a complex Unix command. The cryptic nature of Unix is such that even the most seasoned Unix professional may have trouble deciphering such a command.

Regarding the terms commands and scripts, you should note that any command may become a script if it is encapsulated into a file for execution. Hence, find . –print can be a command if executed from the prompt, or a script if placed into a file.

Building a Complex Unix Command from Scratch


A complex, one-line script is really composed of several simpler commands connected by the pipe operator (|). We will start by how to build a one-line script to kill all the Oracle processes on your server. Then we will see how to build one-line script to find files that contain a specific text string.

A script to kill all Oracle processes


This is a common Unix script used by Oracle DBAs  when a database is locked up, and Server Manager cannot be used to stop the database in more “gentle“ fashion.

To begin, the Unix kill command is used to kill a process. The basic format of the kill command is as follows:

            Kill –9 PID1 PID2 PID3 …PIDn

The trick is to be able to identify and kill only the Oracle processes. That’s done by stringing several commands together. The resulting one-line script looks like this:

ps –ef|grep “ora_”|grep –v grep|grep $ORACLE_SID|
awk ‘{print $2}’|xargs kill –9

We ‘ll walk through the process of building the command. To begin, we want to get a list of active processes on the server. We can do that using the following command:

            ps –ef

If we execute ps –ef on our server, we’ ll see a long list of processes -  both for Oracle and for many other things. However, we want to limit your output to only those processes that are related to the Oracle Database. The grep command can be used to do this. Oracle background process names always begin with “ora_”, so piping the output of ps –ef through grep “ora_” will remove all but the Oracle background processes. For example:

>ps –ef |grep “ora_”

            oracle       12011              1           0           Dec 06                 ora_dbwr_JAP
            oracle       12789     20202           0        12:10:55       0:00      grep ora_
            oracle       13202              1           0           Dec 06                 ora_smon_JAP
            oracle       14983              1           0           Dec 06                 ora_arch_JAP
            oracle       10209              1           0           Dec 06                 ora_pmon_JAP
            oracle         2090              1           0           Dec 06                 ora_reco_JAP
            oracle       10404              1           0           Dec 06                 ora_lgwr_JAP
            oracle       10403              1           0           Dec 06                 ora_dbwr_TEST
            oracle       10401              1           0           Dec 06                 ora_lgwr_TEST

In the above output as we can see it includes the process that’s running grep command. Pipe this output through grep –v grep to remove the grep command, so you don’t kill your own process. The –v option makes grep work in a way that’s opposite its usual manner. Whereas grep finds and includes strings, grep –v excludes strings. In this next example, we’ ll see that the grep line is now missing from the output:

>ps –ef |grep “ora_”|grep –v grep

            oracle       12011              1           0           Dec 06                 ora_dbwr_JAP
            oracle       13202              1           0           Dec 06                 ora_smon_JAP
            oracle       14983              1           0           Dec 06                 ora_arch_JAP
            oracle       10209              1           0           Dec 06                 ora_pmon_JAP
            oracle         2090              1           0           Dec 06                 ora_reco_JAP
            oracle       10404              1           0           Dec 06                 ora_lgwr_JAP
            oracle       10403              1           0           Dec 06                 ora_dbwr_TEST
            oracle       10401              1           0           Dec 06                 ora_lgwr_TEST



Next, we should filter out all processes except those for the current ORACLE_SID. That way we delete the background processes only for that one instance instead of for all instances (if there are multiple database instance running). Do that by grepping for the SID name:

>ps –ef |grep “ora_”|grep –v grep|grep $ORACLE_SID

            oracle       12011              1           0           Dec 06                 ora_dbwr_JAP
            oracle       13202              1           0           Dec 06                 ora_smon_JAP
            oracle       14983              1           0           Dec 06                 ora_arch_JAP
            oracle       10209              1           0           Dec 06                 ora_pmon_JAP
            oracle         2090              1           0           Dec 06                 ora_reco_JAP
            oracle       10404              1           0           Dec 06                 ora_lgwr_JAP

Now that we have an accurate list of processes that you want to kill, you can use the awk command to get the process ID (PID) for each of these processes. The PID is in the second column, so we will use the awk ‘{print $2}’ command to display only that column:

>ps –ef |grep “ora_”|grep –v grep|grep $ORACLE_SID|
awk ‘{print $2}’

12011
13202
14983
10209
  2090
10404

Now we have a list of process Id numbers for the Oracle background processes. For the last step, we use the xargs command to pipe the list of PIDs to the kill command. For example:

>ps –ef |grep “ora_”|grep –v grep|grep $ORACLE_SID|
awk ‘{print $2}’|xargs kill –9

Now that we’ve created this compound command, we can assign it to a Unix alias or we can put it in a file and make it a shell script so that we can execute it with a single short command.

Note: Not all shells support aliases. For example, if we are using the Bourne shell we will not be able to use aliases.



The following command assigns the new compound command to an alias named kill_oracle:

alias kill_oracle = “ps –ef |grep “ora_”|grep –v grep|grep $ORACLE_SID|awk ‘{print $2}’|xargs kill –9”

By placing the command to create the alias in your .profile file, we’ll have it available every time you sign on to Unix. By using an alias, you encapsulate the command without the burden of placing the command into a script file. Now, entering the alias kill_oracle at the command prompt will cause your command to run, which will kill all Oracle background processes for the instance to which $ORACLE_SID points.

A script to find all files containing a specific string


In Unix, it is not easy to find files that contain specific strings. Now we will explore a way to quickly build a command that will allow us to find a file that contains a particular character string.

Using commands such as xargs, we can quickly generate Unix scripts to perform many useful tasks. Suppose that we have created a script to create database TEST. Unfortunately, we have completely forgotten the name and location of the script file, and we need a Unix command to locate it. The example here demonstrates how you can leverage the xargs command to quickly create a complex command that searches for our lost file.

We will begin by writing a command that will display all filenames on the server. This syntax is quite simple in Unix, as the find command can be used to return a list of every file on the server starting from your current directory:

            >find . –print

            /home/oracle/wylie/sqlnet.log
            /home/oracle/wylie/abc.sql
            /home/oracle/wylie/tablespace.sql
            /home/oracle/wylie/create1.sql
            /home/oracle/wylie/export.dmp
            /home/oracle/wylie/create2.sql
            /home/oracle/wylie/create3.sql
            /home/oracle/wylie/a.txt



We now have a complete list of all the Unix files under our current directory. The next step is to pipe this list of filenames to the grep command to search for files containing the string CREATE_DB_TEST. Because the grep command accepts a filename as an argument, you can use xargs to execute a grep command to search each file for the string we need:

            find . –print|xargs grep –i create_db_test

The –i option tells grep to ignore case. We can execute this new command at the Unix prompt, and we’ll see that it quickly finds the file we are seeking:

            >find . –print|xargs grep –i create_db_test

This ability to take a basic Unix command and pipe the output into another command is a fundamental principle of Unix shell programming for Oracle.

Unix Server Environment


Here are some handy Unix commands that will make it easier for use to navigate in our Unix environment. Firstly we will see at commands that can be automatically executed when we sign on to Unix as the Oracle user. There is a special file in our home directory in which we can place Unix commands that we want automatically executed when we sign on to the system. If we use Korn shell, this file is named .profile. if we use C shell, it will be called .cshrc.

We will also see how to create a standard Unix prompt, wrap SQL in Unix script, and write a utility to quickly change all files in a directory.

Set a Standard Unix Prompt


Placing the following code snippet in our .profile file will give you a Unix prompt that identifies our current server name, database name, and working directory. This can help prevent you from accidentally running a command against the wrong database. Note that I have my prompt go to a new line after displaying the information, so that I have a full 79 characters in which to type my Unix commands.

            #*********************************************************************
            # Standard Unix Prompt
            #*********************************************************************
            PS1=”
            `hostname`*\${ORACLE_SID}-\${PWD}
            >”

Here is what the prompt looks like after we have executed the PS1 command shown in the previous example. Note now the prompt changes when you change directories.

            agj1*JAP-/home/oracle
            >pwd

            /home/oracle

            agj1*JAP-/home/oracle
            >cd /home2/dmp/treasury

            agj1*JAP-/home2/dmp/treasury
            >

Create Useful Unix Aliases for Oracle


Here we will see how we can place a list of helpful Unix aliases in the .profile file of a Unix Oracle User.

An alias is a Unix shortcut whereby we can define a short name to use in place of long Unix command. For example, we can create a shortcut called “log” that would execute the Unix cd (change directory) command to take us to the Unix directory where our alert log is located:

            alias log = ‘cd $DBA/$ORACLE_SID/bdump’

The following example shows how aliases such as these can be used in place of typing a long command:

            $log
            $pwd
            /home/oracle/app/oracle/admin/JAP/bdump
            $

Any alias can be removed easily with the Unix unalias command. For example, to remove the log alias, we would enter the command unalias log.

Place a SQL*Plus Script in a Unix Shell Wrapper


Novice to Unix often find it convenient to execute SQL commands directly from the Unix prompt, without having to enter SQL*Plus each time. The following script shows how to create a Unix shell wrapper for any set of SQL*Plus commands. The Unix script in this example is named run_sql.ksh, and it invokes SQL*Plus to execute a SELECT statement followed by the SQL*Plus script contained in the file /home/oracle/abc.sql:

$cat run_sql.ksh

#!/bin/ksh

#First, we must set the environment . . . . .
ORACLE_SID=mysid
export ORACLE_SID
ORACLE_HOME=\`cat /etc/oratab|grep ^$OARCLE_SIDKcut –f2 –d’:’`
export ORACLE_HOME
PATH=$ORACLE_HOME/bin:$PATH
export PATH

$ORACLE_HOME/bin/sqlplus system/passwd<<!

SELECT * FROM v\$database;
@/home/oracle/abc.sql

exit
!

We can also execute a script directly from the command line, provided we have set ORACLE_HOME and ORACLE_SID in our Unix environment. For example:

$sqlplus system/manager @abc






**********************************************