Professional Documents
Culture Documents
Tips File
UNIX Tips
Cron Jobs
If you want to see all your cron jobs just type crontab -l
If you want to edit a cron jobs just type crontab -e
Lines that begin with "#" are considered comments and are ignored.
An environment setting is of the form
NAME = VALUE
Cron will look at a special environment variable, MAILTO. Any output generated by your cron jobs will be sent to the address
specified by MAILTO (if it is not specified it will be sent to the owner of the crontab). If MAILTO is defined by empty (MAILTO=""),
no mail will be sent.
The format of the cron table entry includes five (5) time fields followed by a command. Commands are executed when the time
specified by the date fields matches the current time. The five time fields are as follows:
Field
Allowed Values
minute
0-59
hour
0-23
day of month 0-31
month
1-12 (or names, see below)
day of week
0-7 (0 or 7 is Sun, or use names)
A field may be an asterisk (*), which indicates all values in the range are acceptable. Ranges of numbers are allowed, i.e. "2-5" or "811", and lists of numbers are allowed, i.e. "1,3,5" or "1,3,8-11". Step values can be represented as a sequence, i.e. "0-59/15", "1-31/3",
or "*/2".
Names can be used for the "month" and "day of week" fields. Use the first three letters (case-insensitive) of the particular month or day.
Ranges or lists of names are not allowed.
Examples:
MAILTO="someone@somewhere.com"
15 1 * * * [COMMAND]
Explanation: executes the command [COMMAND] at 1:15 AM every day
40 23 1 * * [COMMAND]
Explanation: executes the command [COMMAND] on the first of every month at 11:40 PM
0-30/10 9,17 * * 1-5 [COMMAND]
Explanation: executes the command [COMMAND] on Monday-Friday (1-5) every 10 minutes for the first half hour (0-30/10) of the 9
AM and 5 PM hours (9,17)
0 */4 * jan sun [COMMAND]
Explanation: executes the command [COMMAND] on each Sunday in January at midnight, 4 AM, 8 AM, noon, 4 PM, and 8 PM
30 4 1,15 * fri [COMMAND]
Explanation: executes the command [COMMAND] at 4:30 AM on the 1st and 15th of each month, plus every Friday
0 0 19 8 * [COMMAND] or
0 0 19 aug * [COMMAND]
esta es una linea de ejemplo:
00 20 * * * /usr/bin/find / -name core -exec rm -f {} \;
minute hour monthday month weekday command
1/48
10/12/2014
Tips File
http://www.pafumi.net/tips.htm
2/48
10/12/2014
Tips File
SETUP Display
If you have problems with the display, try the following in your startup file:
if ( $?DISPLAY == 0 ) setenv DISPLAY `who -m | cut -f 2 -d "(" | cut -f 1 -d ")"`:0.0
- To copy a directory structure (Directory, sub-directories, and all their files)
cp -rp
- Checking space on a disk
df -tk
- Show size of directories (All files under a specific directory)
du -sk
- Useful grep options
grep -c This counts the number of lines that contain the pattern
grep -i Ignore upper/lower case
grep -l Print only the name of the files that contain the pattern. Does not repeat file names.
- Count the number of files in a directory
ls | wc -l
- How to send a message to everyone on a UNIX machine
1. Create a file that contains the message
2. $ wall < [filename] ( Ex: wall < message )
3. You may need to specify the directory 'wall' is in. /usr/sbin/wall < message
3/48
10/12/2014
Tips File
The above command does this for the whole document without confirming, if
you would like to confirm each change use the command:
:%s,[string to replace], [replacing string], gc
This will stop after each search, type a y to confirm the change
svrmgrl
If a database process id is killed, rather than being shutdown properly via svrmgrl, then it will leave memonry and semaphores,
which may prevent the db from being recreated. Do the following to clean it up.
1. Run the UNIX command, 'ipcs -a'. You may want to stretch your screen as wide as it will go to get all the data returned to be
on one line.
2. Look for the line where the value for the column NATTCH is 0. This is the Memory for your killed process that you need to
delete.
3. Get the id# for that line from the ID column (first column)
4. Run the command 'ipcrm -m id#' to delete this memory
5. Figure out which line in the Semaphores zone is for your database.
If there are multiple lines, you may be able to determine which one by comparing the value in the NSEMS column to value of
'processes=XX' in your init.ora.
If only one line matches, then that is the line you need to delete.
If you delete the wrong line you will crash someone else's database.
If you cannot find a distinct line, you may want to try shutting down databases on the system until you can get one distinct line.
Once the line is identified, you need to remove it also.
6. Again, get the id# for that line from the first column.
7. Run 'ipcrm -s id#
- To lock archive file for updating
co -l tele.html
- To unlock
ci -u tele.html
4/48
10/12/2014
Tips File
5/48
10/12/2014
Tips File
/usr/bin/isainfo -kv
On AIX
$ getconf -a | grep KERN
$ file /usr/lib/boot/unix*
On HP-UX
/usr/bin/ getconf KERNEL_BITS
/usr/bin/file /stand/vmunix
Output:
eth0
You can change ip address using ifconfig command itself. To set IP address as 192.168.1.5, enter command:
# ifconfig eth0 192.168.1.5
6/48
10/12/2014
Tips File
GATEWAY=10.10.29.65
Save and close the file. Restart networking::
# /etc/init.d/network restart
or
# service network restart
Make sure you have correct DNS server defined in /etc/resolv.conf file:
# vi /etc/resolv.conf
Setup DNS Server as follows:
nameserver 10.0.80.11
nameserver 10.0.80.12
nameserver 202.67.222.222
Save and close the file. Now you can ping the gateway/other hosts:
$ ping 10.0.80.12
You can also check for Internet connectivity with nslookup or host command:
$ nslookup yahoo.com
Review the configuration. Type
ifconfig
METHOD 2
You can also execute the following command from the X Window and it will show you the GUI Network Tool:
$ system-config-network &
METHOD 3
If you dont have X windows GUI installed type the following command at shell prompt:
# system-config-network-tui &
Change the HOST NAME
Make sure you are logged in as root:
vi /etc/sysconfig/network
Look for the HOSTNAME line and replace it with the new hostname you want to use. In this example I want to replace localhost with
redhat9.
HOSTNAME=redhat9
When you are done, save your changes and exit vi.
Next we will edit the /etc/hosts file and set the new hostname.
vi /etc/hosts
In hosts, edit the line that has the old hostname and replace it with your new one.
192.168.1.110 redhat9
7/48
10/12/2014
Tips File
reboot
This file was automatically generated by the /lib/udev/write_net_rules program, run by the persistent-net-generator.rules rules file. Simple
delete it and reboot the system to recreate the same. This should fix the problem:
# /sbin/ifconfig | grep "^eth"
Sample outputs:
eth0
eth1
Link encap:Ethernet
Link encap:Ethernet
HWaddr 00:0C:29:F3:E4:14
HWaddr 00:0C:29:F3:E4:1E
You need to remove the MAC address in /etc/sysconfig/networking-scripts/ifcfg-eth*. To find out current MAC address, enter:
# ifconfig -a | grep eth1 | grep HWaddr | awk '{ print $5}'
# ifconfig -a | grep eth2 | grep HWaddr | awk '{ print $5}'
Sample outputs:
DEVICE="eth0"
BOOTPROTO="dhcp"
NM_CONTROLLED="yes"
ONBOOT="yes"
HWADDR="00:0C:29:69:0C:4A"
Save and close the file. Restart the network service, enter:
# service network restart
Note=
The relevant filename is slightly different in other Linux distributions. For example, in Debian, the filename is
/etc/udev/rules.d/z25_persistent-net.rules
8/48
10/12/2014
Tips File
new disk on the guest operating system. The second option, "Use an existing virtual disk", allows you to mount a disk from
another virtual machine. I like to do this with my "source" drive. I have one virtual disk that I've made that has all the Oracle and
Linux CDs on it, that way I can just mount it to the machine I need when I have to do a new install instead of copying the
binaries I need across disks, its definitely a big time saver. The last option is to "Use a physical disk", this allows you to mount a
local physical disk to the operating system. This option is akin to NFS mounting a drive to a virtual machine. To add a new disk
we select the "Create a new virtual disk" option and select the "Next >" button.
Next we want to select the type of disk. So in this step we want to select "SCSI (Recommended)" and the "Next >" button.
Now we want to set the size of the disk we are creating. One of the nice features of VMWare is that you don't have to allocate all
of the disk when you create it. So if you create a 40 GB disk it doesn't have to take it all right away, the disk will grow as your
virtual machine needs it.
This is actually pretty simple in that you decide what you want to physically call the disk and where to put it. .vmdk is the
extension for VMWare virtual disks. After we name the disk we can select the "Finish" button which adds the disk to the virtual
machine.
Boot the virtual machine
2- Adding the Disk to Linux System
To see all your disks and its size type:
# sfdisk -s
/dev/sda: 23068672
/dev/sdb: 31457280
Start
1
End
3916
Blocks
31455238+
Id
83
System
Linux
Start
End
Blocks
Id
System
Here I see that this is empy, so I can proceed with this one:
Enter n, p, 1, specify the size (leave defaults to use the full disk)
n
p
p
Partition number (1-4): 1
First cylinder (1-1566, default 1):
Using default value 1
Last cylinder or +size or +sizeM or +sizeK (1-1566, default 1566):
Using default value 1566
Command (m for help): w
--> write table to disk and exit
The partition table has been altered!
Calling ioctl() to re-read partition table.
Syncing disks.
Now that we've create the partition, we now want to format the first with the new file system. I've decided to use ext3 filesystem for
this disk
So, to format the new partition we enter the command mkfs -t ext3 /dev/sdb1. This command makes a new files system with the type t
http://www.pafumi.net/tips.htm
9/48
10/12/2014
Tips File
ext3 on the /dev/sdb1 partition, this is the first partition on the sdb disk.
# mkfs -t ext3 /dev/sdb1
Size
20G
145M
2.4G
30G
After we open the fstab file in the previous step we add the following line:
/dev/sdb1
/u02
ext3
defaults
1 1
The first column is the partition name, the second is the default mount point, the third is the filesystem type.
The fourth is the mount options, in this case I used default which mounts the drive rw, suid, dev, exec, auto, nouser and asynchronous.
The 5th and 6th options are for the dump and fsck options. If dump is set to 1 the filesystem is marked to be backed up, if you are going
to have sensitive material on the drive its a good idea to set it to 1. If fsck is set to greater than 1, then the operating system uses the
number to determine in what order fsck should be run during start up. If it is set to 0 it will be ignored such as in the case of a cdrom
drive since its a solid state disk. For more information on the fstab file check out this article:
http://www.tuxfiles.org/linuxhelp/fstab.html
Lastly, we write and quit the file with the :wq command.
Finally I will make oracle the owner of that disk:
#
#
#
#
mkdir /u02/oradata
cd /u02
chown oracle /u02/oradata
chgrp dba /u02/oradata
10/48
10/12/2014
Tips File
DBMS_SYS_SQL
DBMS_SQL
DBMS_UTILITY
DBMS_DESCRIBE
DBMS_JOB
DBMS_STANDARD
DBMS_OUTPUT
PIDL
4- Run the following Script to check pinned/unpinned packages
SELECT substr(owner,1,10)||'.'||substr(name,1,35) "Object Name",
' Type: '||substr(type,1,12)||
' size: '||sharable_mem ||
' execs: '||executions||
' loads: '||loads||
' Kept: '||kept
FROM v$db_object_cache
WHERE type in ('TRIGGER','PROCEDURE','PACKAGE BODY','PACKAGE')
-- AND executions > 0
ORDER BY executions desc,
loads desc,
sharable_mem desc;
http://www.pafumi.net/tips.htm
11/48
10/12/2014
Tips File
;;
esac
Test the script created. To test the script created above, without rebooting do the following:
su - root
/etc/init.d/dbora start (for startup)
/etc/init.d/dbora stop
(for shutdown)
12/48
10/12/2014
Tips File
13/48
10/12/2014
Tips File
The file nmo, nmb , oradism etc ... in the ORACLE_HOME/bin directory are owned by root user in 10g.In 9i the list
may be different.
We can execute the following command to find the files, which are not owned by oracle owner
$ cd $ORACLE_HOME
$ find . ! -user <oracle_owner> | xargs ls -l | tee /tmp/list.txt
For Example:
$ find . !
-rwsr-x---rwsr-s---rwsr-s---r-sr-s---rw-r-----
l | tee /tmp/list.txt
19:00 ./bin/extjob
18:47 ./bin/nmb
18:47 ./bin/nmo
2006 ./bin/oradism
2005 ./rdbms/admin/externaljob.ora
Check and make a note of the ownership of the files, which are listed as the result of the above command. The list will be also
redirected to the file /tmp/list.txt.
4) Change the ownership of oracle database software by using recursive chown command.
Consider if the current owner of oracle software is "oracle92" who is from "dba" group, you want to change it to a new user "oracle"
and your oracle software is installed in the directory "/app/oracle/product/ora92" then you should do:
$ cd /app/oracle/product
$ chown -R oracle:dba ora92
(You require root access or help of your System administrator for the same.)
The new owner should be also from the same group as like the current owner. You can verify it by using the id command.
$ id <user_name >
Consider your current user is "oracle92" and the group is "dba" then "id oracle92" will give output as uid=1003(oracle92) gid=103(dba)
where 1003, oracle92 is the userid and the user name respectively, 103 and dba is the groupid and group name. The new owner
oracle should be also from the same group dba
5) The recursive chown command will change the ownership of all the files in the Oracle Home. So as root user ,change the
ownership of the files which are listed in the step 3 to the respective users using a chown.
For example:
After recursive chown
$ ls l $ORACLE_HOME/bin/extjob
-rwsr-x--- 1 oracle dba 65319 Jan 8 19:00 ./bin/extjob
6) All the folders that belong to oracle installation are found in ORACLE_HOME except the Oracle Central Inventory.The location of
the Central Inventory usually found from the oraInst.loc file, which contains the path as
"inventory_loc=< path >/oraInventory"
You have to change the ownership of the oraInventory also to the new owner.
(oraInst.loc file exists in /var/opt/oracle or /etc/oracle by default)
In 9i Oracle Universal Installer (OUI) is also found outside the ORACLE_HOME.The location of OUI is found in the oraInventory
from a file called "oui.loc" which contails the path for
"InstLoc=< path >/oui".
You have to change the ownership of this also to the new owner. (In 10g OUI is found inside Oracle Home by default.)
OS Authentication
OS authentication allows Oracle to pass control of user authentication to the operating system. Non-priviliged OS authentication
connections take the following form.
sqlplus /
sqlplus /@service
When a connection is attempted from the local database server, the OS username is passed to the Oracle server. If the username is
recognized, the Oracle the connection is accepted, otherwise the connection is rejected.
First, create an OS user, in this case the user is called "diego". Once you created that, if you try to login as sqlplus "/ as sysdba" it will
fail:
The connections failed because we have not told Oracle the users are OS authenticated. To do this, we must create an Oracle user, but
first we must check the value of the Oracle OS_AUTHENT_PREFIX initialization parameter.
SQL> SHOW PARAMETER os_authent_prefix
http://www.pafumi.net/tips.htm
14/48
10/12/2014
Tips File
NAME
TYPE
VALUE
------------------------------------ ----------- -----------------------------os_authent_prefix
string
ops$
SQL>
As you can see, the default value is "ops$". If this is not appropriate it can be changed using the ALTER SYSTEM command, but for now
we will use this default value.
Now we know the OS authentication prefix, we can create a database user to allow an OS authenticated connection. To do this, we
create an Oracle user in the normal way, but the username must be the prefix value concatenated to the OS username. So for the OS
user "tim_hall", we would expect an Oracle username of "ops$tim_hall" on a UNIX or Linux platform.
-- UNIX
CREATE USER ops$diego IDENTIFIED EXTERNALLY;
GRANT CONNECT TO ops$diego;
The situation is complicated slightly on Windows platforms as the domain or machine name forms part of the username presented to
Oracle. On Windows platforms you would expect an Oracle username of "OPS$DOMAIN\TIM_HALL" for the Windows user
"tim_hall".
-- Windows
CREATE USER "OPS$ORACLE-BASE.COM\DIEGO" IDENTIFIED EXTERNALLY;
GRANT CONNECT TO "OPS$ORACLE-BASE.COM\DIEGO";
When using a Windows server, there is an additional consideration. The following option must be set in the
"%ORACLE_HOME%\network\admin\sqlnet.ora" file.
SQLNET.AUTHENTICATION_SERVICES= (NTS)
With the configuration complete, now you can connect as that "diego" user.
http://www.pafumi.net/tips.htm
15/48
10/12/2014
Tips File
SID_LIST_LSNR2666 =
(SID_LIST =
(SID_DESC =
(GLOBAL_DBNAME = lx10r2.us)
(ORACLE_HOME = /u01/app/oracle/product/10.2.0.1)
(SID_NAME = lx10r2)
)
)
Here, the database alias is "lx10r2.us". Normally, when you specify multiple address lines for an alias, Oracle will attempt the first and
if that fails will attempt the second. This might actually work for the poster, but would still pound port 1666 until it couldn't handle any
connections and THEN try port 2666. The key to having a somewhat even distribution over the two listeners is by using the
(LOAD_BALANCE=ON) parameter.
Suppose Machine01 is down, then every new SQL*NET connection using service 10gexpress will automatically login to Machine02.
However, there is one restriction, the SID must be the same on both machines. This feature can provide guaranteed login for application
servers and for the Oracle Parallel Server.
Prespawned server sessions. You can tell the listener to start up a pool of idle server processes. When a connection request is made, it
doesn't have to start a server process; it just hands one of the idle processes to the client (and then starts a new connection in its own
time). This is configured in LISTENER.ORA, in the SID_LIST_LISTENER section, as follows:
SID_LIST_LISTENER =
(SID_LIST =
(SID_DESC =
(SID_NAME = yourSID)
(PRESPAWN_MAX = 50)
(PRESPAWN_LIST =
(PRESPAWN_DESC = (PROTOCOL = TCP) (POOL_SIZE = 5)
(TIMEOUT = 2))))
)
PRESPAWN_MAX: if there are over 50 sessions connected to the database, the listener won't prespawn any more.
POOL_SIZE: the listener will maintain an idle pool of 5 server processes.
TIMEOUT: after a client disconnects, the listener will keep the freed-up server process around for two minutes, waiting for a new
connection request, before killing that process.
http://www.pafumi.net/tips.htm
16/48
10/12/2014
Tips File
Multiple listeners with load balancing. You can start multiplelisteners on a server, and reference all of the listeners in the
TNSNAMES.ORA file. When a client makes a connection request, the SQL*Net client will randomly pick one of the listeners to
contact.
In LISTENER.ORA, specify multiple listeners as in:
# Define listener A...
STARTUP_WAIT_TIME_LISTENER_A = 0
CONNECT_TIMEOUT_LISTENER_A = 10
LISTENER_A=
(ADDRESS_LIST =
(ADDRESS =
(PROTOCOL = TCP)
(HOST = yourHost.domain)
(PORT = 1521)))
SID_LIST_LISTENER_A =
(SID_LIST =
(SID_DESC =
(SID_NAME = yourSID)
(PRESPAWN_MAX = 50)))
# Define the second listener...
STARTUP_WAIT_TIME_LISTENER_B = 0
CONNECT_TIMEOUT_LISTENER_B = 10
LISTENER_B=
(ADDRESS_LIST =
(ADDRESS =
(PROTOCOL = TCP)
(HOST = yourHost.domain)
(PORT = 1522)))
SID_LIST_LISTENER_B =
(SID_LIST =
(SID_DESC =
(SID_NAME = yourSID)
(PRESPAWN_MAX = 50)))
Shut down all oracle software (confirm with "ps -fu oracle" command).
# make the change
http://www.pafumi.net/tips.htm
17/48
10/12/2014
Tips File
# change lookups
vipw [...change oracle UID to 103, GID to 21]
vi /etc/group [change dba GID to 21]
It might be a little slow, you can experiment with the recursive option of chown instead of using find. Or, instead of -exec option of
'find', pipe output to xargs command. Just be sure you handle symbolic links correctly. (Your SA should understand all of this, in case
you don't).
18/48
10/12/2014
Tips File
SSH Tunnel
Situation:
Windows box connects to work using SafeNet Secure VPN Client
Once connected, I have to ssh to a box (let's call it 192.168.2.29), and once connected to that box, I have to ssh to another box that has
the DB Server (192.168.1.28).
I'd like to access the DB Server directly from my PC (if possible).
This are the steps that I performed:
- Open PuTTY and load your saved session.
- Choose Tunnels in the category section. Then in the "source port" section, put any port number that is not in use (example: 1234).
- In the destination text box enter the IP address of the host name (192.168.1.28 in my case) followed by a colon and the destination
port number(1521). Remember to click on the ADD button.
- Save your settings in PUTTY.
- Then modify your tnsnames.ora with something like this:
PROD =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = 127.0.0.1)(PORT = 1234))
)
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = CCOM)
)
)
- Then ssh to the 1st server
- Finally type the following to connect and create the tunnel to the second server:
ssh -L 1234:192.168.1.28:1521 oracle@192.168.1.28
The previous command will create a "tunnel", any request going to 92.168.1.28:1521 will be forwarded to 127.0.0.1:1234.
- Now you can connect from the Original box to the DB
Database Automatic Failover On Another Database
A-on SERVER1:
1-open tnsnames.ora file in this path D:\oracle\product\10.2.0\db_1\NETWORK\ADMIN
2-edit the tnsnames.ora file and modfiy your database service to be like this
ORC1=
(DESCRIPTION=
(FAILOVER=on)
(ADDRESS=(PROTOCOL=tcp)(HOST=SERVER1)(PORT=1521))
(ADDRESS=(PROTOCOL=tcp)(HOST=SERVER2)(PORT=1521))
(CONNECT_DATA=(SERVICE_NAME=ORC1)))
and add another service for the the database ORC2 on SERVER2
ORC2 =
(DESCRIPTION =
(ADDRESS =
(PROTOCOL = TCP)
(HOST = SERVER2)
(PORT = 1521)
)
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = ORC2)
http://www.pafumi.net/tips.htm
19/48
10/12/2014
Tips File
)
)
B-On SERVER2
1-open tnsnames.ora file in this path D:\oracle\product\10.2.0\db_1\NETWORK\ADMIN
2-edit the tnsnames.ora file and modfiy your database service to be like this
ORC2=
(DESCRIPTION=
(FAILOVER=on)
(ADDRESS=(PROTOCOL=tcp)(HOST=SERVER2)(PORT=1521))
(ADDRESS=(PROTOCOL=tcp)(HOST=SERVER1)(PORT=1521))
(CONNECT_DATA=(SERVICE_NAME=ORC2)))
and add another service for the the database ORC1 on SERVER1
ORC1 =
(DESCRIPTION =
(ADDRESS =
(PROTOCOL = TCP)
(HOST = SERVER1)
(PORT = 1521)
)
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = ORC1)
)
)
C-at this point your databases can failover on each other
D-To test that your configuration is working try to connect an application to or TOAD to the ORC1 database with schema scott/tiger
and then open SQLPLUS and shutdown this database
it will be automatically switched on the other database ORC2
http://www.pafumi.net/tips.htm
20/48
10/12/2014
Tips File
1. Windows
1. HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\FileSystem\NtfsDisableLastAccessUpdate = 1
2. Redhat Linux(s)
1. chattr +A file_name per Oracle control, data and log file
2. chattr -R +A directory_name per Oracle SID data directory
3. Edit /etc/fstab for the Oracle Home and/or data file systems
Example: /dev/sda6 / home ext3 defaults,noatime 1 1
VNC - Install Oracle Software on Remote Linux Server
If not already done so download and install a client version of VNC so you can connect to the server. There are many out there, for the
purpose of this post I use UltraVNC.
You can download a free version from http://www.uvnc.com/download/index.html
1- By default VNC Server is installed in your RedHat and OEL OS, but it is not configured. The way VNC works is when started it
creates a client instance for the user and binds it to a specific port. So if have an account on the Linux box you can setup a VNC Server
session for that user, you dont need to be root. For the purpose of this document Im going to use oracle as the user to setup a VNC
Session as this is the user I want use to install the software. However to start the VNC Service you must be root.
As the root user run the following command:
service vncserver start
Starting VNC server: no displays configured
OK
3- You will be ask to supply password information. This is what you will enter when connecting from your desktop client. This
password is also independent of the actual Linux user password.
You will require a password to access your desktops.
Password:
Verify:
xauth: creating new authority file /home/oracle/.Xauthority
Creating default startup script /home/oracle/.vnc/xstartup
Starting applications specified in /home/oracle/.vnc/xstartup
Log file is /home/oracle/.vnc/lisa.nz.oracle.com:1.log
4- As you can see a new instance server_name:1 has been created. If you were to run the vncserver command again another instance
server_name:2 will be created.
If you are going through a firewall you will need to ensure that the port 5901 (port 1) is open between your client desktop and the Linux
Server.
Depending on the options chosen at install time a firewall could be in place. The simplest way to disable this is using the command.
You will need to be root.
service iptables stop
This will stop the firewall while you install. If you just want to add a port to the accepted lists use the firewall UI. You will need to be
root.
system-config-security-level
Now you are ready to connect to the server via the VNC. Using the software installed in step one start the VNC Client. You should be
prompted for the server and port.
Other Options:
Launch VNC with X Desktop $HOME/.vnc/xstartup
#!/bin/sh
# Uncomment the following two lines for normal
desktop:
unset SESSION_MANAGER
exec /etc/X11/xinit/xinitrc
[ -x /etc/vnc/xstartup ] && exec /etc/vnc/xstartup
[ -r $HOME/.Xresources ] &&xrdb $HOME/.Xresources
xsetroot -solid grey
vncconfig -iconic &
xterm -geometry 80x24+10+10 -ls -title "$VNCDESKTOP
Desktop" &
#twm&
http://www.pafumi.net/tips.htm
21/48
10/12/2014
Tips File
Tar (and zip) the Oracle home (probably you encounter some errors, some files in the bin directory are set to owner root, this is
alright):
$ tar czf /path/to/tarfile.tgz --exclude "*.log" --exclude "network/admin/*" --exclude "$(hostname)*" --exclude "/dbs/*"
*
Run clone.pl:
./clone.pl ORACLE_HOME="/path/to/new/home" ORACLE_BASE="/path/to/base" -defaultHomeName
Here is the output of clone.pl on a testsystem: (see how clone.pl calls runInstaller!)
./runInstaller -clone -waitForCompletion "ORACLE_HOME=/oracle/db/11.2.0.1_test" "ORACLE_BASE=/oracle" -defaultHomeName defaultHomeName -silent -noConfig -nowait
Starting Oracle Universal Installer...
.
Checking swap space: must be greater than 500 MB. Actual 1852 MB Passed
Preparing to launch Oracle Universal Installer from /tmp/OraInstall2010-07-02_04-34-52PM. Please wait ...Oracle Universal
Installer, Version 11.2.0.1.0 Production
Copyright (C) 1999, 2009, Oracle. All rights reserved.
.
You can find the log of this install session at:
/oracle/oraInventory/logs/cloneActions2010-07-02_04-34-52PM.log
.................................................................................................... 100% Done.
.
.
.
Installation in progress (Friday, July 2, 2010 4:36:13 PM CEST)
............................................................................. 77% Done.
Install successful
.
Linking in progress (Friday, July 2, 2010 4:36:40 PM CEST)
Link successful
.
Setup in progress (Friday, July 2, 2010 4:41:23 PM CEST)
Setup successful
.
.
End of install phases.(Friday, July 2, 2010 4:47:18 PM CEST)
Starting to execute configuration assistants
The following configuration assistants have not been run. This can happen because Oracle Universal Installer was invoked
with the -noConfig option.
-------------------------------------The "/oracle/db/11.2.0.1_test/cfgtoollogs/configToolFailedCommands" script contains all commands that failed, were
skipped or were cancelled. This file may be used to run these configuration assistants outside of OUI. Note that you may
have to update this script with passwords (if any) before executing the same.
The "/oracle/db/11.2.0.1_test/cfgtoollogs/configToolAllCommands" script contains all commands to be executed by the
configuration assistants. This file may be used to run the configuration assistants outside of OUI. Note that you may
have to update this script with passwords (if any) before executing the same.
.
-------------------------------------WARNING:
The following configuration scripts need to be executed as the "root" user.
/oracle/db/11.2.0.1_test/root.sh
To execute the configuration scripts:
1. Open a terminal window
2. Log in as "root"
3. Run the scripts
.
The cloning of OraHome1 was successful.
Please check '/oracle/oraInventory/logs/cloneActions2010-07-02_04-34-52PM.log' for more details.
As the clone.pl output indicates, root.sh needs to be run after the clone.pl command.
http://www.pafumi.net/tips.htm
22/48
10/12/2014
Tips File
Database Tips
Writing to the alert log
If you want to write a message to the alert log, you can use the undocumented KSDWRT procedure of the DBMS_SYSTEM package.
This procedure has two parameters, the first one must be "2" to write to the alert file, the second one is the message you want to write.
Here is an example:
execute sys.dbms_system.ksdwrt(2,to_char(sysdate)|| ' -- ');
Use 1 instead of 2 to write to the trace file
Use 3 to write to both.
Example:
exec sys.dbms_system.ksdwrt(2, 'CUS-00001: message from me'||chr(10)||'On another line');
--> In the alert.log file:
Wed Jun 25 19:49:30 2003
CUS-00001: message from me
On another line
Name
http://www.pafumi.net/tips.htm
Address_id
23/48
10/12/2014
Tips File
--------00001
00002
00003
00004
---------------Fred Bloggs
Joe Smith
Jane Doe
Sue Jones
Address
------Address_id
---------00057
00092
00113
---------00057
00092
00111
Address_Desc
------------------------1, Acacia Avenue, Anytown
13, High Street, Anywhere
52, Main Road, Sometown
returns:
NAME
---------Fred Bloggs
Joe Smith
ADDRESS_DESC
-----------1, Acacia Avenue, Anytown
13, High Street, Anywhere
returns:
NAME
---------Fred Bloggs
Joe Smith
Jane Doe
Sue Jones
ADDRESS_DESC
-----------1, Acacia Avenue, Anytown
13, High Street, Anywhere
Note the two new rows for Jane Doe and Sue Jones. These are the people who do not have matching records on the ADDRESS table.
Sue Jones had an address_id on her PERSON record, but this didn't match an address_id on the ADDRESS table. ( Probably a data
inconsistency ). Jane Doe had NULL in her PERSON.ADDRESS_ID field, which obviously doesn't match any address_id on the
ADDRESS table.
Note that the outer join is created by including (+) on the WHERE clause which joins the two tables. The (+) is put against the columnname on the deficient table, ie. the one with the missing rows. It is very important to put the (+) on the correct table: putting it on the
other table will give different results. eg. the query:
returns:
NAME
---------Fred Bloggs
Joe Smith
ADDRESS_DESC
-----------1, Acacia Avenue, Anytown
13, High Street, Anywhere
52, Main Road, Someplace
Managing Dates
You can use fractions with sysdate (or any date column) to add hours, minutes and/or seconds. For hours, use a denominator of 24; for
minutes use 1440; for seconds: 86400.
For example "sysdate + 3/24" will add 3 hours, "sysdate + 5/1440" will add 5 minutes; "sysdate + 45/86400" will add 45 seconds. You
can use values like "sysdate + 30/24" to add one day +6 hours if you need to. Example:
SELECT to_char(sysdate,'dd-mon-yyyy hh:mi:ss'),
TO_CHAR(SYSDATE + 10/1440,'dd-mon-yyyy hh:mi:ss') FROM DUAL;
Using Oracle functions for dates
An alternative to this method is to use the numtodsinterval function. Example to add 2 hours:
SELECT to_char(sysdate, 'DD/MON/YY HH24:MI:SS'), to_char(sysdate + numtodsinterval(2, 'HOUR'), 'DD/MON/YY HH24:MI:SS')
FROM dual;
TO_CHAR(SYSDATE,'D TO_CHAR(SYSDATE+NU
------------------ -----------------17/JAN/06 12:50:53 17/JAN/06 14:50:53
Here the numtodsinterval function is doing the work of dividing 2/24 for hours.
http://www.pafumi.net/tips.htm
24/48
10/12/2014
Tips File
Valid options for the numtodsinterval are DAY, HOUR, MINUTE, or SECOND. Here is an example using MINUTE.
When working with minutes the numtodsinterval function is much more readable.
SELECT to_char(sysdate, 'DD/MON/YY HH24:MI:SS'), to_char(sysdate + numtodsinterval(45, 'MINUTE'), 'DD/MON/YY HH24:MI:SS')
FROM dual;
TO_CHAR(SYSDATE,'D TO_CHAR(SYSDATE+NU
------------------ -----------------17/JAN/06 12:50:09 17/JAN/06 13:35:09
Add any sqlplus commands here that are to be executed when a user
starts SQL*Plus on your system
http://www.pafumi.net/tips.htm
25/48
10/12/2014
-----
Tips File
Rebuilding Indexes
You can use the ALTER INDEX REBUILD command to change the storage and tablespace parameters for an existing index without
having to drop it.
The following is an example of an index rebuild via this command. It's storage parameters are changed to use an initial extent size of
3MB and a next extent size of 500K. It is also being moved from the USR7 tablespace to the IDX7 tablespace.
http://www.pafumi.net/tips.htm
26/48
10/12/2014
Tips File
Collect Statistics
In 11g You are encouraged to use AUTO_SAMPLE_SIZE for ESTIMATE_PERCENT .
In 11g AUTO_SAMPLE_SIZE is very fast compared to earlier versions and gives accuracy of close to 100 % sample size.
AUTO_SAMPLE_SIZE uses a new Hash-based Sampling for Column Statistics.
By default 11g will collect histograms - to avoid them you need to use method_opt => 'for all columns size 1')
If performance is still a problem you can try to setting back OPTIMIZER_FEATURES_ENABLE='10.2.0.1' and this improved
performance.
Create dictionary statistics
EXEC dbms_stats.gather_schema_stats('SYS',options => 'GATHER',estimate_percent => DBMS_STATS.AUTO_SAMPLE_SIZE,method_opt
=> 'FOR ALL COLUMNS SIZE AUTO',cascade => TRUE);
or
=> DBMS_STATS.AUTO_SAMPLE_SIZE,
Or
EXEC dbms_stats.gather_dictionary_stats;
For a Table
exec dbms_stats.gather_table_stats('&USER','&TABLE_NAME',estimate_percent => DBMS_STATS.AUTO_SAMPLE_SIZE, degree => 5,
cascade => TRUE);
For a Schema
execute dbms_stats.gather_schema_stats (ownname => '&USER', estimate_percent => DBMS_STATS.AUTO_SAMPLE_SIZE, degree => 5,
cascade => true);
For the DB
execute dbms_stats.gather_database_stats(estimate_percent => DBMS_STATS.AUTO_SAMPLE_SIZE, degree => 5, cascade => true);
http://www.pafumi.net/tips.htm
27/48
10/12/2014
---------
Tips File
http://www.pafumi.net/tips.htm
28/48
10/12/2014
Tips File
DBMS_OUTPUT.PUT_LINE(chr(13));
END IF;
-- Reset count to 0.
mcount := 0;
-- End of Loop 1
END LOOP;
END;
/
SET FEEDBACK ON
-- - - - - - - - - - - - - - - - - - - - - - - - - Script ends here - - - - - - - - - - - - - - - - - - - - - - - - - -
Archiving ON
By default, archive logs will be written to the flash recovery area. If you do not want to write archive logs to the flash recovery area you
can set the parameter LOG_ARCHIVE_DEST_n to the location in which you wish to write archive logs.
Remember that the default location for Archive Log Files is USE_DB_RECOVERY_FILE_DEST. You can determine its path by
looking at the parameter RECOVERY_FILE_DEST:
SQL> show parameter recovery_file_dest
NAME
-----------------------------------db_recovery_file_dest
db_recovery_file_dest_size
TYPE
----------string
big integer
VALUE
-----------------------------C:\app\flash_recovery_area
6G
You can switch to the log file to see that an archive is written to archive log location.
alter system switch logfile;
OPTIONAL
You can also define the format of the archive log files with the log_archive_format parameter. To define the values for
log_archive_format, the following variables can be used in the format:
%s log sequence number
%S log sequence number, zero filled
%t thread number
%T thread number, zero filled
%a activation ID
%d database ID
%r resetlogs ID that ensures unique names are constructed for the archived log files across multiple incarnations of the database
Using uppercase letters for the variables (for example, %S) causes the value to be fixed length and padded to the left with zeros.
Example:
alter system set log_archive_format='ARCH_%T_%S_%r.arc' scope=both;
Archiving OFF
Steps Required To Take A Database In Archive Log Mode And Alter It To No Archive Log Mode (for ever)
SELECT log_mode FROM gv$database;
archive log list;
show parameter recovery;
--To see where the parameter DB_RECOVERY_FILE_DEST is pointing (if used)
or
show parameter LOG_ARCHIVE_DEST_1;
SHUTDOWN IMMEDIATE;
http://www.pafumi.net/tips.htm
29/48
10/12/2014
Tips File
STARTUP MOUNT;
ALTER DATABASE NOARCHIVELOG;
ALTER DATABASE OPEN;
alter system set LOG_ARCHIVE_DEST_STATE_1=DEFER scope=both;
alter system Set LOG_ARCHIVE_DEST_1='' SCOPE=both;
SELECT log_mode FROM gv$database;
archive log list;
As always, first step in troubleshooting Oracle is to check an alert.log. If you do not know where is it then perform:
select value from v$parameter where name = 'background_dump_dest';
VALUE
-------------------------------------------------------------------------------c:\oracle\product\diag\rdbms\FGUARD\trace
Resolution
All looks that your db_recovery_file_dest_size is full with archive logs. To check that and be certain, perform:
show parameter db_recovery_file_dest_size;
NAME
TYPE
VALUE
------------------------------------ ----------- -----------------------------db_recovery_file_dest_size
big integer 2G
Because Oracle has no space to create new archived log file it freeze all operations and could wait in this state until eternity if you do
not help him!
So you have two (three) solutions to overcome this.
1) Enlarge db_recovery_file_dest_size (from 2 to 3 GB in our case)
alter system set db_recovery_file_dest_size=3G scope=both;
3) Just delete archive logs (what I'll show as easiest way but I prefer previous two options on any production installations). I'll do that
with RMAN as best way for that:
rman target / nocatalog
RMAN> delete archivelog all;
http://www.pafumi.net/tips.htm
30/48
10/12/2014
Tips File
Now, let us look again in alert log to see that situation has changed (as we expect):
Wed Dec 23 20:52:57 2009
db_recovery_file_dest_size of 2048 MB is 2.21% used. This is a
user-specified limit on the amount of space that will be used by this
database for recovery-related files, and does not reflect the amount of
space available in the underlying filesystem or ASM diskgroup.
kcrrdmx: Successful archiving of previously failed ORL
Archiver process freed from errors. No longer stopped
Wed Dec 23 20:53:00 2009
AUD: Audit Commit Delay exceeded, written a copy to OS Audit Trail
Wed Dec 23 20:53:00 2009
Thread 1 advanced to log sequence 148 (LGWR switch)
Current log# 1 seq# 148 mem# 0: C:\ORACLE\PRODUCT\ORADATA\FGUARD\REDO01.LOG
As you can see db_recovery_file_dest_size of 2048 MB is 2.21% used shows that we have emptied all!
Then connect as SYS and issue the following command to archive the remaining logs:
ALTER SYSTEM ARCHIVE LOG ALL;
This command archives all unarchived log files. This should cause the archiver to start.
If you are using 10g, you can use the following to recompile ONLY the invalid ones:
EXEC DBMS_UTILITY.compile_schema(schema => 'SCOTT', compile_all => 'FALSE');
3- UTL_RECOMP
The UTL_RECOMP package contains two procedures used to recompile invalid objects. As the names suggest, the
RECOMP_SERIAL procedure recompiles all the invalid objects one at a time, while the RECOMP_PARALLEL procedure performs
the same task in parallel using the specified number of threads. The following examples show how these procedures are used:
-- Schema level.
EXEC UTL_RECOMP.recomp_serial('SCOTT');
EXEC UTL_RECOMP.recomp_parallel(4, 'SCOTT');
-- Database level.
EXEC UTL_RECOMP.recomp_serial();
EXEC UTL_RECOMP.recomp_parallel(4);
There are a number of restrictions associated with the use of this package including:
Parallel execution is perfomed using the job queue. All existing jobs are marked as disabled until the operation is complete.
The package must be run from SQL*Plus as the SYS user, or another user with SYSDBA.
http://www.pafumi.net/tips.htm
31/48
10/12/2014
Tips File
The package expects the STANDARD, DBMS_STANDARD, DBMS_JOB and DBMS_RANDOM to be present and valid.
Runnig DDL operations at the same time as this package may result in deadlocks.
4- utlrp.sql and utlprp.sql
The utlrp.sql and utlprp.sql scripts are provided by Oracle to recompile all invalid objects in the database. They are typically run after
major database changes such as upgrades or patches. They are located in the $ORACLE_HOME/rdbms/admin directory and provide a
wrapper on the UTL_RECOMP package. The utlrp.sql script simply calls the utlprp.sql script with a command line parameter of "0".
The utlprp.sql accepts a single integer parameter that indicates the level of parallelism as follows:
0 - The level of parallelism is derived based on the CPU_COUNT parameter.
1 - The recompilation is run serially, one object at a time.
N - The recompilation is run in parallel with "N" number of threads.
Both scripts must be run as the SYS user, or another user with SYSDBA, to work correctly.
DBMS_XPLAN
In version 9, Oracle finally provides a utility that formats the contents of the plan table. The plan table is one that is used to hold the
results of an "Explain Plan" for a particular SQL statement. The output from the explain plan shows the anticipated optimizer execution
path, along with the estimated cost of the statement without actually executing the statement against the database. The DBA or
developer first needs to create the plan table. The DDL for this table is in the $ORACLE_HOME/rdbms/admin/utllxplan.sql file. The
next step in using dbms_xplan is running Explain Plan for a statement.
explain plan for select * from flowdocument where amount > 100000;
The command above will populate the plan table with the data returned from the optimizer. Next, the dbms_xplan utility can be used to
view the output
select * from table(dbms_xplan.display);
---------------------------------------------------------------------| Id | Operation
| Name
| Rows | Bytes | Cost |
---------------------------------------------------------------------|
0 | SELECT STATEMENT
|
|
1 |
168 |
3 |
|
1 | TABLE ACCESS FULL
| FLOWDOCUMENT |
1 |
168 |
3 |
----------------------------------------------------------------------
Another way
SELECT a.rowid
FROM &&table_name a
WHERE a.rowid > (SELECT min(b.rowid)
FROM &&table_name b
WHERE a.&&column_name = b.&&column_name);
Then:
DELETE from &&table_name
WHERE a.rowid > (SELECT min(b.rowid)
FROM &&table_name b
WHERE a.&&column_name = b.&&column_name);
http://www.pafumi.net/tips.htm
32/48
10/12/2014
Tips File
*** This script will remove duplicate rows. Suppose a table contains 3 columns. To remove the duplicate rows write the following
command, where a and b are aliases of the same table.
Delete from table_A a
where a.rowid > any (select rowid
from Table_B b
where a. = b.
and a. = b.
and a. = b.);
Shrinking Datafiles
For example, if a datafile is 100Meg in size, and 70Meg of the datafile is currently in use. Then atleast 70Meg must be left in the
datafile. The RESIZE parameter of the ALTER DATABASE command is used to reclaim the space.
ALTER DATABASE datafile '/db01/oracle/fix/data03.ora' resize 80M;
The procedures above document how to drop a temporary tablespace that is not the default temporary tablespace for the database. You
will know fairly quickly if the tablespace is a default temporary tablespace when you are greeted with the following exception:
SQL> DROP TABLESPACE temp;
drop tablespace temp
*
ERROR at line 1:
ORA-12906: cannot drop default temporary tablespace
In cases where the temporary tablespace you want to resize (using the drop/recreate method) is the default temporary tablespace for the
database, you have several more steps to perform, all documented below. The first step you need to perform is create another temporary
tablespace (lets call it TEMP2). The next step would be to remove the temporary tablespace you want to resize from being the default
temporary tablespace (in our example, this will be a tablespace named TEMP) by making TEMP2 the default. Drop / recreate the
TEMP tablespace to the size you want. Finally, make the newly created TEMP tablespace your default temporary tablespace for the
database and drop the TEMP2 tablespace. A full example session is provided below:
CREATE TEMPORARY TABLESPACE temp2
TEMPFILE '/data/u01/app/oracle/oradata/CCOM/TEMP2.dbf' SIZE 5M REUSE
AUTOEXTEND ON NEXT 1M MAXSIZE unlimited
http://www.pafumi.net/tips.htm
33/48
10/12/2014
Tips File
Transportable Tablespaces
1- Make the tablespace Read-Only = alter tablespace xxxx read only;
2- Export it connecting as sys as sysdba = exp file=tt.dmp log=tt.log tablespaces=xxxx transportable_tablespaces=y
3- Copy the .dmp file and the data_files to the destination
4- Put the tablespace back in write mode = alter tablespace xxxx read write;
5- In the destination offline and drop the tablespace if exists
6- Import = imp file=tt.dmp log=tt.log tablespaces=test transportable_tablespace=y datafiles=(......., ........)
Orakill Utility
The orakill utility is provided with Oracle databases on Windows platforms. The executable (orakill.exe) is available to DBA's to kill
Oracle sessions directly from the DOS command line without requiring any connection to the database.
In the Unix world, a DBA can kill a shadow process by issuing the kill -9 commands from the Unix prompt. Unix is able to provide this
capability given that the Unix operating system is based on processes that fork other processes. All processes can be listed by using the
ps Unix command. The Oracle background processes will be listed separately from all of the Oracle sessions since they have their own
process.
Unlike the Unix operating system, Windows systems are thread-based. The background processes and sessions are all contained within
the ORACLE.EXE executable and are not listed in the "Processes" tab of Windows Task Manager.
The orakill utility serves the same purpose as kill -9 in Unix. The command requires the instance and the SPID of the thread to kill. The
following query will return the SPID for each user connected to the database:
select a.username, a.osuser, b.spid
from v$session a, v$process b
where a.paddr = b.addr
and a.username is not null;
USERNAME
---------------------------SCOTT
AMOORE
DMOORE
OSUSER
-----------------------Scott
Alex
Dave
SPID
----3116
4760
768
Given the SPID for each user listed above, the session for any user can be killed with the orakill command.
C:\oracle9i\bin>orakill ORCL92 4760
Why does Oracle provide a utility to kill sessions from the DOS prompt when a DBA could kill a user session from within Oracle? The
following command will also kill the user session:
alter system kill session(sid, serial#);
The sid and serial# used in the command above can be obtained from the v$session view. There are a few reasons a DBA could use
orakill instead of the alter system kill session command.
1. The alter system statement will not clear the locks if any exist. Instead, the session will remain connected until it times out, then the
http://www.pafumi.net/tips.htm
34/48
10/12/2014
Tips File
session is killed and the locks are released. The orakill command will kill the thread and the locks instantly.
2. A DBA may not be able to gain access to a SQL prompt due to a runaway query consuming all system resources. In this case, the
session can be killed without ever logging in to the database.
The orakill utility should be used as a last resort only. If the session cannot be killed more gracefully (via alter system kill session), or
the instance is inaccessible via SQL, then orakill can be used to terminate the offending session.
Background processes should not be terminated, only user sessions. Killing a background process can cause serious Oracle errors and
can bring the database down.
35/48
10/12/2014
Tips File
Generating a string of printable 20 characters. This will output a string of all characters that could possibly be printed.
select dbms_random.string('P', 20) str from dual;
STR
-------------------jqPJ3IxH%]Ij}_Y2j!p[
This will randomly sample 1% of the rows, multiple the count of them x 100 to get a rough estimate of the amount of rows in the table.
You can also randomly sample by blocks for better performance but possibly less random:
SELECT * FROM EMP SAMPLE BLOCK (1);
Again, this samples roughly 1% of the table by blocks, which may not be 1% of the actual rows. But this will cause fewer blocks to be
visited and decrease the elapsed time, but if the data is grouped in the table, it may not be very random.
This tool can be used to get a rough idea of the data in the table, or give good estimates when using group functions. For example, a
great use of this would be on a 40 million row table:
SELECT AVG(number_of children) * 20 FROM dependants sample (5);
This will give you an average of the number of dependants by only sampling 5% of the table by only visiting 2 million rows and not 40
million.
http://www.pafumi.net/tips.htm
36/48
10/12/2014
Tips File
Then run:
column ord
noprint
column date_
heading 'Date'
format A15
column no
heading '#Arch files' format 9999999
column no_size heading 'Size Mb'
format 9999999
compute avg of no
on report
compute avg of no_size on report
break on report
select MAX(first_time) ord, to_char(first_time,'DD-MON-YYYY') date_,
count(recid) no, count(recid) * &logfile_size no_size
from v$log_history
group by to_char(first_time,'DD-MON-YYYY')
order by ord;
clear breaks
clear computes
clear columns
Unlocking Users
alter user &username account unlock;
37/48
10/12/2014
Tips File
NAME
TYPE
VALUE
----------------------------- ----------- ---------remote_login_passwordfile
string
EXCLUSIVE
3.
Grant SYSDBA or SYSOPER to users. When SYSDBA or SYSOPER privileges are granted to a user, that user's name and
privilege information are added to the password file.
SQL> grant sysdba to scott;
Grant succeeded.
4.
Confirm that the user is listed in the password file.
SQL> select * from v$pwfile_users;
USERNAME
-----------------------------SYS
SCOTT
SYSDBA
-----TRUE
TRUE
SYSOPER
------TRUE
FALSE
Now the user SCOTT can connect as SYSDBA. Administrative users can be connected and authenticated to a local or remote database
by using the SQL*Plus connect command. They must connect using their username and password, and with the AS SYSDBA or AS
SYSOPER clause:
SQL> connect scott/tiger as sysdba;
The DBA utilizes the orapwd utility to grant SYSDBA and SYSOPER privileges to other database users. The SYS password should
never be shared and should be highly classified.
Step 2
Connect as SYS
shutdown immediate;
startup mount;
38/48
10/12/2014
Tips File
http://www.pafumi.net/tips.htm
39/48
10/12/2014
Tips File
begin
select host_name into v_host_name from v$instance;
dbms_output.put_line('the database server name is ' || v_host_name);
SELECT UTL_INADDR.GET_HOST_ADDRESS(v_host_name) into v_ip_address FROM DUAL;
dbms_output.put_line('the database server ip address is ' || v_ip_address);
end;
/
SELECT host_name, UTL_INADDR.GET_HOST_ADDRESS(host_name) ip FROM v$instance;
Pivot Table
create table VOL_MONTHLY_REPORT
(
COUNT_ITEMS_PROT
COUNT_ITEMS_OPEN
DATECREATED
APPLICATIONID
ARCHIVEDDATE
/
VARCHAR2(16)
NUMBER
DATE
NUMBER(2, 0)
DATE
,
,
,
,
)
SELECT DATECREATED,
DECODE (APPLICATIONID, 3, COUNT_ITEMS_OPEN, NULL) VRA,
DECODE (APPLICATIONID, 4, COUNT_ITEMS_OPEN, NULL) IRD
FROM (SELECT DATECREATED, APPLICATIONID, COUNT_ITEMS_OPEN FROM VOL_MONTHLY_REPORT);
DATECREATED
VRA
IRD
------------------ ---------- ---------01/JAN/07 00:00:00
10
01/JAN/07 00:00:00
20
02/JAN/07 00:00:00
33
02/JAN/07 00:00:00
44
http://www.pafumi.net/tips.htm
40/48
10/12/2014
Tips File
Use the following script to retrieve the SQL statement for a particular user:
select SQL_TEXT from V$SQLAREA
where (address, hash_value)
IN (select SQL_ADDRESS, SQL_HASH_VALUE
from V$SESSION
where SID = &SID);
http://www.pafumi.net/tips.htm
41/48
10/12/2014
Tips File
-- In order to remove a group to increase its size, that group must be inactive:
alter database drop logfile group 2;
alter database add logfile group 2 ('/opt/oracle/oradata/XGUARD/redo02.log') size 600M reuse;
SEQUENCE seq;
seq.NEXTVAL FROM dual;
seq.NEXTVAL FROM dual;
seq.NEXTVAL FROM dual;
http://www.pafumi.net/tips.htm
42/48
10/12/2014
Tips File
FROM user_sequences;
where:
- scott/tiger : username and password of the schema you will connect to.
- 192.168.1.100 : the IP Address for the database server.
- 1521 : database port.
- orcl : db_sid
In order for this to work, you need to add a parameter to the sqlnet.ora file on the database server in this path
$ORACLE_HOME/network/admin
NAMES.DIRECTORY_PATH=(ezconnect,tnsnames)
Flushing the Shared Pool and the Buffer Cache
Prior to Oracle Database 10g, the only way to flush the database buffer cache was to shut down the database and restart it. Oracle
Database 10g now allows you to flush the database buffer cache with the alter system command using the flush buffer_cache
http://www.pafumi.net/tips.htm
43/48
10/12/2014
Tips File
parameter.
The FLUSH Buffer Cache clause is useful if you need to measure the performance of rewritten queries or a suite of queries from
identical starting points. Use the following statement to flush the buffer cache.
ALTER SYSTEM FLUSH BUFFER_CACHE;
ALTER SYSTEM FLUSH SHARED_POOL;
However, note that this clause is intended for use only on a test database. It is not advisable to use this clause on a production database,
because subsequent queries will have no hits, only misses.
Resetting a table's HWM in Oracle 10g
Traditionally, in order to reset the High Water Mark(HWM), the table will be truncated and then reloaded with the new set of
data. But in Oracle 10g, with the help of alter table <xxx> shrink space command, we can reclaim the wasted space in our
database as well as reset the HWM also. But keep in mind, prior to using this command on your table, there are some prerequisites.
1. The tablespace in which the table is present must be of Auto Segment Space Management.
2. Row Movement must be enabled in the table. If it is not enabled at the time of creation, then you can use:
ALTER TABLE <TABLE-NAME> ENABLE ROW MOVEMENT;
Once the above mentioned pre-requisites are satisfied, then you can use the following command to shrink space and reset the
HWM.
ALTER TABLE <TABLE-NAME> SHRINK SPACE CASCADE;
If you just want to only defrag the table and not reset the HWM or reclaim the space due to active DML transactions, you can
use:
ALTER TABLE <TABLE-NAME> SHRINK SPACE CASCADE COMPACT;
In order to see how many empty blocks are still there in the table, first analyze the table and then you can use:
select table_name, blocks, empty_blocks, last_analyzed, global_stats from user_tables where table_name=<TABLE-NAME>;
Print_Table Procedure
The following code will let you select data from SQL*Plus in a nice format:
create or replace procedure print_table ( p_query in varchar2,
p_date_fmt in varchar2 default 'dd-MON-yyyy hh24:mi:ss' )
-- this utility is designed to be installed ONCE in a database and used
-- by all. Also, it is nice to have roles enabled so that queries by
-- DBA's that use a role to gain access to the DBA_* views still work
-- that is the purpose of AUTHID CURRENT_USER
AUTHID CURRENT_USER
is
l_theCursor
integer default dbms_sql.open_cursor;
l_columnValue
varchar2(4000);
l_status
integer;
l_descTbl
dbms_sql.desc_tab;
l_colCnt
number;
l_cs
varchar2(255);
l_date_fmt
varchar2(255);
-- small inline procedure to restore the sessions state
-- we may have modified the cursor sharing and nls date format
-- session variables, this just restores them
procedure restore
is
begin
if ( upper(l_cs) not in ( 'FORCE','SIMILAR' ))
then
execute immediate
'alter session set cursor_sharing=exact';
end if;
if ( p_date_fmt is not null )
then
execute immediate
'alter session set nls_date_format=''' || l_date_fmt || '''';
end if;
dbms_sql.close_cursor(l_theCursor);
end restore;
begin
-- I like to see the dates print out with times, by default, the
-- format mask I use includes that. In order to be "friendly"
-- we save the date current sessions date format and then use
http://www.pafumi.net/tips.htm
44/48
10/12/2014
Tips File
-- the one with the date and time. Passing in NULL will cause
-- this routine just to use the current date format
if ( p_date_fmt is not null )
then
select sys_context( 'userenv', 'nls_date_format' )
into l_date_fmt
from dual;
execute immediate
'alter session set nls_date_format=''' || p_date_fmt || '''';
end if;
----if
http://www.pafumi.net/tips.htm
45/48
10/12/2014
Tips File
Example:
SQL> exec print_table( 'select * from T where a = ''X'' ' );
exec print_table( 'select * from center ' );
exec print_table( 'select * from center centercode = ''TDBN5'' ' );
100
Using non pairwise comparison you compare a single value (manager_id) extracted from the current record with a set of single values
extracted by the subquery.
Then you compare a single value (department_id) extracted from the current record with a set of single values extracted by the
subquery
But there are opportunities where you may need to get EXACTLY a specific pair of objects, in that case you can use PAIRWISE
COMPARISON SUBQUERY:
SELECT employee_id, manager_id, department_id
FROM employees
--inner query returns pair of values (108,100), (123,50) and (100,80)
WHERE (manager_id, department_id) IN (SELECT manager_id, department_id FROM employees WHERE first_name = 'John')
AND first_name != 'John'
ORDER BY 1,2,3;
Using pairwise comparison you compare a "vector" of values (manager_id, department_id) extracted from the current record with a set
of vectors of values extracted by the subquery.
The latter executes the subquery only once, while the former executes it twice.
http://www.pafumi.net/tips.htm
46/48
10/12/2014
Tips File
yesterday_size:=today_size;
END IF;
growth_size := today_size - yesterday_size;
INSERT INTO db_growth
VALUES(sysdate,today_size,growth_size);
EXCEPTION
WHEN no_data_found THEN
INSERT INTO db_growth VALUES(sysdate,today_size,0);
DBMS_OUTPUT.PUT_LINE(SQLERRM);
END;
/
3.Submit in DBMS_JOBS
variable jobno number;
begin
dbms_job.submit(:jobno,'DATABASE_GROWTH ;',trunc(sysdate+1) + 4/24,'trunc(sysdate+1) + 4/24');
commit;
end;
/
print :jobno
The SPACE_USAGE column shows how many bytes the object actually consumes.
The SPACE_ALLOC reports the size, in bytes, of space used by the object.
The QUALITY column indicates the quality of the output as follows:
- GOOD - The data for the timepoint relates to data within the AWR repository with a timestamp within 10% of the interval.
- INTERPOLATED - The data for this timepoint did not meet the GOOD criteria but was based on data gathered before and after the
timepoint.
- PROJECTED - The timepoint is in the future, so the data is estimated based on previous growth statistics.
http://www.pafumi.net/tips.htm
47/48
10/12/2014
Tips File
ORDER BY START_TIME;
OR
Use TRANSLATE function as given below
Example
SELECT translate('##$$$1$$2#3&&!!__!', '[0-9]#$&&!_','[0-9]') FROM dual;
OR
SELECT translate('##$$$123&&!!__!', '0#$&&!_','0') FROM dual;
Number of Transactions
set
col
col
col
col
col
set
lines 120
"Total Commits" for 999,999,999
"Total Rollbacks" for 999,999,999
"Total User Calls" for 999,999,999
"Avg Daily DML Transactions" for 999,999,999
"Avg Daily User Calls" for 999,999,999
lines 120 heading on pages 100
The above query should give you an idea of how "busy" their database is since it was started.
The column showing "Total User Calls" is counting the number of select statements.
Total Commits Total Rollbacks Total User Calls Uptime in days Avg Daily DML Transactions Avg Daily User Calls
------------- --------------- ---------------- -------------- -------------------------- -------------------15,448
6
41,001
11.9276852
1,296
3,437
If they want to know the #transactions / hour then you could execute the following query:
set pages 9999;
column c1 heading
column c2 heading
column c3 heading
column c4 heading
column c5 heading
column c6 heading
break on report
compute sum of c3
compute sum of c4
http://www.pafumi.net/tips.htm
48/48