This is an old revision of the document!
Table of Contents
Handy_scripts
SQL
List all instances running on a server
Sounds simple enough and indeed pre 12.1, is was as easy as either
0@@
or this one is safer in case you have an underscore character in your SID name!!
1@@
but now we have the added complication of CDB/PDB (container / pluggable databases) so a fair bit more work is needed!
2@@
Run a command or script on all databases in tnsnames.ora
Very handy if you have a global tnsnames.ora accessible to all clients.<br /> So from a client install, this has access to all databases.<br /> Any files created can be created on the client so no need to scp to all the machines to recover spool files etc.<br /> Downside: Cannot connect as sysdba across tns so password will need to be known for whatever user is used.
3@@
Run a command or script on all databases in oratab
4@@
5@@
Run an SQL command on behalf of another user
It can be used to execute any sql command as a specified user provided this procedure is created in sys schema.<br />
- not got this working properly yet *
6@@
Run a script on all databases listed in tnsnames.ora
Can run an SQL command file on all SID/SERVICE found in a tnsnames.ora file. I use this from a client laptop having a global tns file on it.<br /> This way it's not necessary to copy the file onto every host before executing it. Any files created by the script will be created on the client.
7@@
List invalid objects
set lines 200 set pages 200 col obj format a40 select owner||'.'||object_name obj , object_type from dba_objects where 1=1 and status = 'INVALID';
Recompile all invalid objects
@?/rdbms/admin/utlrp.sql
See how much space is left in the flash recovery area (FRA)
8@@
or
9@@
How far back can we flashback?
10@@
DBA privs tables
DBA_AQ_AGENT_PRIVS DBA_COL_PRIVS DBA_PRIV_AUDIT_OPTS DBA_REPGROUP_PRIVILEGES DBA_ROLE_PRIVS DBA_RSRC_CONSUMER_GROUP_PRIVS DBA_RSRC_MANAGER_SYSTEM_PRIVS DBA_SYS_PRIVS DBA_TAB_PRIVS DBA_WM_SYS_PRIVS DBA_WORKSPACE_PRIVS
Schedule a shell job
begin
dbms_scheduler.create_program ( program_name => 'myshelljob'
, program_action => '/home/oracle/scripts/shell.sh'
, program_type => 'EXECUTABLE'
, comments => 'Run a shell'
, enabled => TRUE
);
end; /
Start the job
begin
dbms_sheduler.create_job ( job_name => 'myshelljob'
, program_name => 'myshelljob'
, start_date =>
);
/
What statement is a user running?
11@@
See what statements all users are running
Useful to see what is happening when process limit is reached
12@@
A logminer session
Mine all SQL statements in a 10 minute period
13@@
Huge Pages
14@@
Pretty longops listing
15@@
16@@
or attach to the impdp job and it shows percentage done.
17@@
Apply the database patch after the ORACLE_HOME has been patched
18@@
Show how much archivelog data is generated per day
A companion script for 'how many log switches in a day'
19@@
Abort a hanging database even when sysdba cannot connect
Unable to connect to database with sqlplus / as sysdba because audit file cannot be created?
Instead of just killing the pmon process, there is a kinder (and more useful) way to kill the database.<br /> Use the hidden, undocumented 'prelim' switch parameter to sqlplus to make a connection to the database without creating SGA session data structures.<br /> It can be very useful for hang analysis so the possible cause can be found after the database has been restarted.
20@@
Lists Oracle session with kill session statement all ready to go
disconnect attempts to kill the o/s processes too. kill doesn't.
21@@
How much space is being used by a guaranteed restore point?
22@@
Get statistics for LOB columns in a table
23@@
badprivs.sql
Check to see if any ordinary users have privileges / access / grants / rights they should not have
24@@
Generate a list of tablespaces ready for a migration
25@@
List the privileges assigned to users on directories
table_name is the name of the directory…
26@@
List the privileges assigned to users on packages/procedures
table_name is the name of the package…
27@@
List the system privileges assigned to a user (used to copy user as or clone user as)
Maybe this one is better Extract ddl with "dbms metadata.get ddl"
SELECT LPAD(' ', 2*level) || granted_role “USER PRIVS” FROM (
SELECT NULL grantee, username granted_role
FROM dba_users
WHERE username LIKE UPPER('%&uname%')
UNION
SELECT grantee, granted_role
FROM dba_role_privs
UNION
SELECT grantee, privilege
FROM dba_sys_privs)
START WITH grantee IS NULL CONNECT BY grantee = prior granted_role;
or
SELECT path FROM (
SELECT grantee,
sys_connect_by_path(privilege, ':')||':'||grantee path
FROM (
SELECT grantee, privilege, 0 role
FROM dba_sys_privs
UNION ALL
SELECT grantee, granted_role, 1 role
FROM dba_role_privs)
CONNECT BY privilege=prior grantee
START WITH role = 0)
WHERE grantee IN (
SELECT username FROM dba_users WHERE lock_date IS NULL AND password != 'EXTERNAL' AND username != 'SYS')
OR grantee='PUBLIC'
or
for a migration from 10g…
28@@
or for a migration on 11g…!
29@@
Move datafiles between filesystems
Set the relevant datafile offline
30@@
Rename the files on the filesystem using o/s commands
31@@
Run the relevant alter commands to inform the control files of the new locations
32@@
Recover the datafiles
33@@
Set the relevant datafile online
34@@
Check all is well with the datafiles by using an appropriate statement
35@@
Rename a datafile on 12c
If you're lucky enough to be on 12c, it's one command - no need to offline the datafile!
36@@
Pass parameter/argument into perl one-liner script from shell
Trick? Just use ARGV to pass them in…
37@@
or
38@@
or export the variable from shell and access it via the ENV hash
39@@
Return epoch seconds in Perl
40@@
or to convert a specific day of the year to epoch seconds
41@@
or for a specific date (careful though - month is 0-11 not 1-12!…<br />
42@@
or more long-winded but delimited by anything…<br /> Supply the date/time in any delimited format. Eg. YYYY-MM-DD:HH:MI
43@@
Return epoch seconds in DOS/VBS/Windows
Paste this code into epoch.vbs
44@@
and call from a DOS box like this
45@@
Return date from epoch seconds in Perl
46@@
Return epoch seconds from julian day number in Perl
47@@
Extract specific pieces of a date from an epoch timestamp in Perl
48@@
Return epoch seconds in Shell (linux)
49@@
Return date from epoch seconds in Shell (linux)
50@@
Return epoch seconds in PL/SQL
You cannot just use sysdate as that is timezone sensitive… (epoch seconds are in UTC/GMT)
51@@
How long has this instance been up (in minutes)?
52@@
Return date from epoch seconds in SQL
53@@
A database overview using the sys.plato package
exec plato.help; or exec plato.complete('HTM');
List datafiles for a tablespace
54@@
Show graph of available and free space in tablespaces
55@@
Another method for calculating free space in tablespace using segments
56@@
Work out maximum possible size of a datafile
57@@
or, as tablespaces can have block sizes differing from that of the init.ora parameter…
58@@
Show size and maxsize at datafile level
datafiles
59@@
tempfiles
60@@
Resize the online redo logfiles
Found a more concise, smarter way of doing it here - oracle-wiki.net<br /> Switching logs too often? Redolog files too small?<br />
- Show current log groups
61@@
- Create additional (bigger) groups
62@@
or if you use multiple members…
63@@
- Switch archivelogs until the new ones are current and the old ones are inactive
64@@
If the old logs are not yet inactive, checkpoint the database
65@@
- Drop the old groups
66@@
Increase the existing size of a datafile
67@@
Increase the max size of a tempfile
68@@
Find out what processes are using the temp tablespace
Temporary tablespace is used for sorting query results. Find them with this.
69@@
Increase the maximum size of a datafile
Although this can be set lower than existing size, try not to. It makes the reports look weird!
70@@
Find schemas (users) with objects created outside their default tablespace
Indexes could be a notable exception if they are created in an index tablespace
71@@
Add a datafile to a tablespace
'unlimited' will default to the maximum datafile size for the current db_block_size
72@@
List all datafiles with their size
73@@
Database size (How big is my database?)
There are different interpretations of what constitutes the size of a database…<br /> Is it the space allocated to the datafiles or only the space taken up by the data? Are tempfiles included? Are redo logs included? etc…
74@@
Drop datafile from temp tablespace
Database is completely stuck because the temporary tablespace has grown to fill all available room.<br /> Look around for at least some log files to delete in order to get connected (audit files, sqlnet logs, listener logs)<br /> Once connected, change the default temporary tablespace to a small one so we can remove the original.
75@@
76@@
I found trying to drop the datafile like this didn't work, just hung there (probably active tranactions)…
77@@
So did it like this…
78@@
… an alternative would be to find the sessions using the temp space and kill them…
79@@
Then to be neat and tidy, rename the temp2 tablespace back to temp.
80@@
Although the last statement will not work until any transactions using it have been rolled back or committed.
List files that are in hot-backup mode
set lines 100 set pages 100 col name format a60
select df.name , b.status , to_char(time, 'hh24:mi:ss dd/mm/yyyy') time from v$datafile df , v$backup b where 1=1 and df.file# = b.file# and b.status = 'ACTIVE' order by b.file#;
Waiting for snapshot control file enqueue
Script to identify sessions causing RMAN to hang because of 'waiting for snapshot control file enqueue' message
81@@
Info on blocking processes
82@@
session doing the blocking
83@@
sessions being blocked
84@@
info on session doing the blocking
85@@
Show locked objects
set lines 100 set pages 999 col username format a20 col sess_id format a10 col object format a25 col mode_held format a10 select oracle_username||' ('||s.osuser||')' username , s.sid||','||s.serial# sess_id , owner||'.'||object_name object , object_type , decode ( l.block
, 0, 'Not Blocking'
, 1, 'Blocking'
, 2, 'Global'
) status
, decode ( v.locked_mode
, 0, 'None'
, 1, 'Null'
, 2, 'Row-S (SS)'
, 3, 'Row-X (SX)'
, 4, 'Share'
, 5, 'S/Row-X (SSX)'
, 6, 'Exclusive', TO_CHAR(lmode)
) mode_held
from v$locked_object v , dba_objects d , v$lock l , v$session s where 1=1 and v.object_id = d.object_id and v.object_id = l.id1 and v.session_id = s.sid order by oracle_username , session_id;
Show which row is locked
select do.object_name , row_wait_obj# , row_wait_file# , row_wait_block# , row_wait_row# , dbms_rowid.rowid_create (1, ROW_WAIT_OBJ#, ROW_WAIT_FILE#, ROW_WAIT_BLOCK#, ROW_WAIT_ROW#) from v$session s , dba_objects do where 1=1 and s.ROW_WAIT_OBJ# = do.OBJECT_ID and sid = &sid;
Check what is audited on a database
86@@
How old is the oldest audit record?
87@@
Check what objects are being audited
88@@
Procedure to delete old audit records
89@@
Job setup to run the audit purge
90@@
A list of all SIDs in oratab that should restart after a server boot
Using awk
91@@
Using perl
92@@
Move the admin directories to a new location
93@@
Check if the Standby database is up-to-date with the primary database
select arch.thread# “Thread” , arch.sequence# “Last Sequence Received” , appl.sequence# “Last Sequence Applied” , (arch.sequence# - appl.sequence#) “Difference” from (
select thread#
, sequence#
from v$archived_log
where 1=1
and ( thread#,first_time ) in (
select thread#, max(first_time)
from v$archived_log
group by thread#
)
) arch
,
(
select thread#
, sequence#
from v$log_history
where 1=1
and ( thread#,first_time ) in ( select thread# ,max(first_time)
from v$log_history
group by thread#
)
) appl
where 1=1 and arch.thread# = appl.thread# order by 1;
Check for gaps on the Standby database
Run this on the standby
94@@
or run this on the Primary to see the latest generated archive…
95@@
and run this on the standby to check for received but not yet applied logs (this could be normal if a lag has been set)…
96@@
Compare the results from Primary and Secondary to detect possible network problems or other errors in shipping.
Ignore case-sensitive passwords in 11g (deprecated in 12c)
97@@
External table for the Alert log (pre 11g)
Modified to use (the better) scripts found on Rene Nyffenegger's site<br /> This script generates the required DDL for the alertlog table
98@@
Alert log (11g+)
This reads the log.xml file (which contains the same information as alert.log)<br /> Show the messages put in the alert log in the last 24 hours
99@@
There is also a fixed table X$DBGDIREXT which returns all file and directory names under diagnostic_dest/diag directory:
100@@
Directory paths available in v$diag_info
101@@
Find out the names of the active trace files for the running processes
102@@
Request was to duplicate a large tablespace from production to test environment
…but rather than copy the terabytes of data, create the destination tablespace with just the most recent months data<br />
See what the source data looks like
103@@
This query produces something like this…
104@@
Capture the tablespace metadata
105@@
produces…
106@@
Capture the tablespace objects' metadata
107@@
Find the partitions with data from the most recent month
108@@
produces…
109@@
Export the data in these partitions
110@@
Drop the old tablespace
111@@
Recreate the tablepspace using the metadata capture above
112@@
Import the tablespace metadata
113@@
Import the last month partition data
114@@
Write to a TCP/IP socket from PL/SQL
115@@
and read from it using netcat in another session
116@@
produces
117@@
Execute a script as a different user
Some things have to be done as the user and cannot be done as sys (eg. creating and dropping jobs or create and drop a database link)<br /> It is possible to login as the user by saving, changing and resetting his password (using identified by values) but using dbms_sys_sql is another option<br /> Create a PL/SQL procedure to drop a db link
118@@
Generate the calls to the procedure with the required parameters
119@@
and this reveals the lines to be executed
120@@
Drop the procedure when finished with it
121@@
or do it as an anonymous block in one go…
122@@
Handling single quote marks inside SQL statements
123@@
Run a script on all databases in /etc/oratab
124@@
Schedule a cron job to run on the last day of each month
125@@
How to tell if a year is a leap year or not - using cal instead of reinventing the wheel
Test: Why is Julian day 0, 17th November 1858?<br /> Pretty comprehensive answer: here and here<br /> Also attempts to answer the question why typing 'cal 09 1752' on Unix systems looks so odd!
126@@
Reset an expired (and/or locked) user password to the same value
Can be used to save user passwords for example in a test environment before destroying them with a copy of production.<br /> Simple, quick and easy version. Run this then pick and choose the statements you want to run.
127@@
More industrialised version. Create a package.
128@@
Call it
129@@
Latch, mutex and beyond
A fine example of how to write scripts from SQL*Plus that interact with the shell underneath<br /> Found here at andreynikolaev.wordpress.com
130@@
shell
Count the number of background processes for a particular SID
131@@
or …this will work with any OS (so long as the process is at the end of the <strong>ps -ef</strong> or <strong>ps -aux</strong> listing
132@@
Pick the columns you want in the ps listing
133@@
Find Oracle errors in the most recent DataPump log files
134@@
Find the 10 largest directories on a particular filesystem
135@@
Find the 10 largest files on a particular mount point
136@@
or
137@@
Split a file in pieces using sed
Using fixed line numbers
138@@
Using line with a /pattern/ on it
139@@
Split a file in pieces using Perl
140@@
Find and display RMAN errors in an RMAN log file
141@@
cmd
Perl
For all files in a directory, replace a keyword (SSIIDD) in a file with another (a parameter)
142@@
Parse tnsnames.ora to get just the service names
and use that to check the listener status
144@@
