Sei sulla pagina 1di 31

t

DB2 9 and Oracle 10g


Comparison Guide

Author: James Dey


Date:
22 February 2007
Version: 2.2
Email:
jdey@macehill.co.uk
Website: http://www.macehill.co.uk

The purpose of this guide is to provide a quick reference to relate DB2 and Oracle
terminology and to provide a comprehensive set of scripts to a DB2/Oracle DBA so
that with some training they are able to fulfil the fole of a development DBA in either
database .

Index
1. Object/code types.......................................................................................................4
2. Column datatypes.......................................................................................................5
3. Database memory model............................................................................................6
3.1 DB2......................................................................................................................6
3.2 Oracle...................................................................................................................6
4. Database basic configuration parameters...............................................................7
5. Database server processes..........................................................................................9
5.1 DB2......................................................................................................................9
5.2 Oracle...................................................................................................................9
6. Database layout........................................................................................................10
7. DB2 lock isolation levels.........................................................................................12
8. Database scripting languages...................................................................................15
9. Database Monitoring................................................................................................16
10. DBA commands.....................................................................................................17
11. Main Differences....................................................................................................29

1. Object/code types
Db2
Dbm cfg
Db cfg
Database manager/Instance
Database
Tablespace
Container
Extent
Page
Bufferpool
Schema
Table
Index
Sequence
View
SQL/PL
Package(collection of static sql access
plans)
(No equivalent)
Control Center
Trigger
db2systm, sqldbcon, db2rhist.asc
Stored procedure
Function
Diagpath (db cfg) default=db2diag.log
(No equivalent)

Oracle
Spfile<sid>.ora
Spfile<sid>.ora
Instance
Database
Tablespace
Datafile
Extent
Blocksize
db_cache_size,
db_$blocksize_cache_size,
db_keep_cache_size
No real equivalent. user=schema in
Oracle
Table
Index
Sequence
View
PL/SQL
(No equivalent)
package (collection of procedures/udfs)
Enterprise Manager
Trigger
control File (control0x.ctl)
stored procedure
Function
<sid>alrt.log
rollback segments/undo tablespace (used
to capture before-update info)

2. Column datatypes
DB2
char
varchar
smallint
integer
bigint
decimal(x,x)
date
time
timestamp
blob
clob
long

Oracle
char
varchar2
number(3,0)
number(6,0)
number(10,0)
number(x,x)
date (to_char(date,DD-MON-YYYY))
date (to_char(date,HH:MM:SS))
date
blob
clob
long

3. Database memory model


3.1 DB2
Instance shared memory (includes audit buffer, monitor heap, fast communication
buffers). Allocated when instance is started.
Database shared memory (bufferpools, locklist, catalog cache, package cache, shared
sort heap, database heap (including log buffer), utility heap. Allocated on first
connection to the database.
Application shared memory. Only allocated in multi-partitioned databases, when
intra-parallelism is turned on or when the connection concentrator is enabled.
Application private memory (sort heap, application heap, query heap, statement heap,
statistics heap, java heap, agent stack). Allocated whenever a db2 agent or subagent is
created to do some work.

3.2 Oracle
System Global Area (SGA) (consists of shared pool, database buffer cache, redo log
buffer, java pool, streams pool and large pool)
Process Global Area (PGA) (sort area, hash area, bitmap merge area, stack etc)
Note: DB2s instance/database/application shared memory roughly correspond
to Oracles SGA and DB2s application private memory roughly corresponds to
Oracles PGA.

4. Database basic configuration parameters


DB2
Database page size
No direct equivalent. You either explicitly
define tablespace/container locations or
DB2 defaults the structure. Theres no
DB2 managed files concept.
newlogpath, overflowlogpath,
mirrorlogpath
No equivalent
No equivalent
No equivalent of flash recovery area.
Backups and archive logs can be saved
anywhere on disk
No direct equivalent. Each database in a
partitioned DB2 database environment is
defined as a DB2_NODE environment
variable.
DB2 doesnt have an in-built queueing
mechanism. Use MQ-Series.
logarchmeth(1 or 2)
database code page, code set,
country/region code, territory
No equivalent. There is no restriction on
the number of open cursors in db2.
No exact equivalent. You can specify the
maximum number of applications/agents
and the individual private memory
threstholds
maxagents/appls
No equivalent. Listener process has to
exist on same machine.
No equivalent. Privileged user groups
and password files are administered
No equivalent. Transactions are rolled
back by reading the transaction logs.
Undo data is not stored separately.
maxagents/appls
self_tuning_mem=on,

Oracle
db_block_size
db_create_file_dest

db_create_online_log_dest_n
db_domain
db_name, db_unique_name
db_recovery_file_dest
db_recovery_file_dest_size
db_unique_name
instance_name

job_queue_processes
log_archive_dest_n,
log_archive_dest_state_n
nls_language, nls_territory
open_cursors
pga_aggregate_target

processes
remote_listener
remote_login_passwordfile
rollback_segments
sessions
sga_target
7

database_memory=automatic,
db_mem_thresh
max_connections, max_coordagents
No equivalent
No equivalent. Transactions are rolled
back by reading the transaction logs.
Undo data is not stored separately.
maxtotfilop
num_iocleaners
dft_prefetch_sz
max_querydegree
softmax
logretain
logbufsz
catalogcache_sz
pkgcachesz
sortheap
buffpage
util_heap_sz

shared_servers
star_transformation_enabled
undo_management, undo_tablespace
db_files
db_writer_processes
db_file_multiblock_record_count
parallel_max_servers
log_checkpoint_interval,
log_checkpoint_timeout
log_archive_start
log_buffer
dictionary cache (part of
shared_pool_size)
library cache (part of shared_pool_size)
sort_area_size
db_cache_size
large_pool_size

5. Database server processes


5.1 DB2
db2wdog - monitors user processes and cleans them up if they fail
db2sysc - monitors server processes
db2gds - spawns new processes
db2fcmdm - handles communication between partitions in a partitioned database
db2pfchr - Prefetches data from disk in to bufferpool
db2pclnr - writes dirty data in the bufferpool down to disk
db2cart - archives redo log files when userexit enabled
db2loggr - reads transaction log files for recovery
db2loggw - writes transaction log files
db2dlock - detects deadlock conditions

5.2 Oracle
PMON - monitors user processes and cleans them up if they fail
SMON - monitors server processes and cleans them up if they fail
MMON - issues alerts when threshold values have been reached and captures table
and index statistics at intervals
MMAN - manages the automatic allocation of shared memory
MMNL - Captures sesson history and computes metrics
DBWR - writes dirty data in the bufferpool down to disk
ARCn - archives redo log files
LGWR - writes redo log files
CKPT - performs a checkpoint at appropriate time

6. Database layout
The same rules go for DB2 as they do for Oracle. i.e.
1. Put indexes in separate tablespaces on separate disks from the table data.
2. Put logs on fast disks, again separate from the index and disks.
3. Keep static/slow changing data in separate tablespaces from dynamic/quick
changing data
4. Size tables so that all the data goes in 1 extent, where possible.
With DB2, you multiplex the control files or transaction logs from the database but
you can, of course, mirror them at the operating system level.
In Oracle, prior to Oracle 9i, you could only define a block size at the database level
and all tablespaces had to use that block size. Since Oracle 9i, you can assign a
different block size at the tablespace level, and you can assign a single buffer cache
for each block size. To retain tables in memory, Oracle has a keep buffer cache.
You can create multiple bufferpools with DB2, which has the advantage that data
stored in memory from your static data tablespace isnt overwritten by data from your
dynamic data tablespace. Oracle now allows you 1 buffer cache for each different
block size.
DB2 has 2 types of tablespaces:1. System managed storage (SMS) creates a tablespace as a set of directory
containers, in which tables and indexes are created as files. As rows are
inserted into a table, the o/s file is extended a page at a time. SMS has the
advantage is that its easy to administer, but has performance problems when
inserting anything other than small amounts of data
2. Database managed storage (DMS) creates a tablespace as file containers
(similar to Oracle datafiles). As rows are inserted, if they fill an extent, then
another extent is allocated for that table within the tablespace container.
DB2 v9 DMS tablespaces now have the equivalent of Oracles autoextend. Prior to
that, youd have to run daily scripts to check how much free space you had in your
DB2 DMS tablespace and proactively increase the tablespace when it was close to
filling up.
With DB2, storage management is defined at the tablespace rather than table level.
This means that tables should be grouped by storage characteristics and allocated
separate tablespaces. Oracles problem is that allowing tables to have different storage
characteristics within the same tablespace leads to fragmentation problems and in a
10

busy system, Oracle can have problems allocating extents to tables. Oracle also has a
maxextents limit which can cause problems if extent allocation isnt monitored
properly. Since 10g, Oracle now has the ability to allocate storage extents at the
tablespace level. i.e. all tables within the same tablespace will have the same initial,
next and extent percentage increase allocations. This makes it easier for the database
engine to manage.
In terms of logging, in Oracle logfiles and sizes are defined in the create database
statement, whereas DB2 defines these using database parameters logfilsiz, logprimary,
logsecond and newlogpath.
Note: Oracle have defined an Oracle Flexible Architecture (OFA) which defines
exactly how mount points, filesystems. directories and files should be named and
located.

11

7. DB2 lock isolation levels


Repeatable read (RR) - this takes and holds read locks on every row which a cursor
could read. These read locks are held until the cursor is closed. This ensures that
another application can not update rows in the cursor set. Additionally, next key locks
are taken out in the index to prevent phantom insert and deletes
Read stability(RS) this takes and holds read locks on every row which is actually
read.
Cursor stability(CS) takes out a read lock on a row currently being read, and
release it once the cursor moves to read the next row.
Uncommitted Read (UR) takes out no read locks. This ensures that another
application can select, insert, update or delete any data.
A common problem identified by Oracle developers is the situation where you need to
lock all the rows in a number of tables e.g. when producing monthly accounts whilst
maintaining reasonable concurrency for the main application users.
There are 3 possible problems which can cause queries to return misleading
information:1. Dirty reads. This is where the UR isolation level is being used and you can see
data which has been updated by another writer application but not yet
committed.
2. Non-repeatable reads. This is where a reader application re-queries the same
set of data within the same transaction and gets different results because
another writer application has committed updated data between the readers 1st
and 2nd read of the dataset.
3. Phantom reads. This is where a writer application has inserted extra rows and
the reader application sees them when he re-queries the data.
By default, Oracles locking level is similar to read stability but only guarantees
statement-level read consistency i.e. if a reader re-queries within the same transaction,
they will get back different data if another writer application has updated or inserted
some of the data and committed. i.e. problems 2 and 3 arent catered for. The only
advantage that Oracles rollback segments give them here is that other writer
applications can update rows that the reader has taken read locks on. As DB2 doesnt
have rollback segments, the writer application is forced to wait until the DB2 reader
application has released the locks
Oracle does have the ability, however, to maintain transaction-level read consistency
by issuing the set transaction read only statement at the beginning of the
12

transaction. The limitation of this is that the reader is not allowed to use any update
commands. It still doesnt cater for the phantom read problem, however. The only
way to deal with this is to issue a lock table <table> in exclusive mode which will
then prevent other writer applications updating that table, making it identical in
operation to DB2.
The manner in which Oracle rollback segments/undo tablespaces work, is that each
time a writer application updates a row, a pre-updated version of the row is saved in
the rollback segments/undo tablespace together with the time that it was updated.
Problems which Oracle users have with rollback segments/undo tablespace are:1. The higher the write transaction rate there is against a table, the larger the
rollback segment/undo tablespace needs to be. This is because the pre-updated
rows have to be kept in the rollback segment/undo tablespace until the writer
application commits his transaction. If there is insufficient room, extents will
be created within the rollback segment until it fills up. At that point, there is no
more room left, so some pre-updated rows will be overwritten. If the reader
application queries a row which has been updated but the copy of the preupdated row has been overwritten then Oracle will return a snapshot too old
message.
2. The larger the rollback segment, the poorer the performance. Rollback
segments are held on disk and are unindexed. Note: Less of a problem with
undo tablespaces which are recommended post Oracle 9i.
3. If a reader application decides to update some of its read information and
another writer application has already updated that row, Oracle will issue a
record has been updated by another user error message. An Oracle
developers only solution to prevent this happening would be to open a select
for update cursor which allows the reader application to update any of the
rows theyve read but prevents any writer applications from updating the rows.
If we assume that Oracle developers constructing the monthly sales report are
unconcerned with phantom rows, and have a long running transaction which reads
data from a very large accounts table then Oracle is perceived to have an advantage.
There are a number of potential solutions which will reduce lock waiting in DB2,
however:1. In DB2 v8, you can release locks when a cursor is closed rather than when a
transaction is committed. This allows DB2 to operate in a similar fashion to
Oracles default behaviour of statement-level consistency only.
2. In DB2 v8, you can create a materialised query table with a deferred refresh
for many of the tables that you want to generate your monthly accounts
against. To generate your monthly accounts, you could then query the
13

materialised query table directly, whilst the normal users continue to update
the base table. Since materialised query tables allow you to put in where
clauses, you can greatly reduce the number of rows which you need to copy
from the very large table. As youll now be querying a table which writer
applications arent accessing, you can be assured that all 3 potential
corruptions arent possible.
3. In previous versions of DB2, you can simulate oracles rollback segments by
creating an on-update trigger against each table which you will be querying.
The trigger will ensure that the old version of a particular row is copied to a
change table (declared as a global temporary table). The base table should also
have an update timestamp in it. Your program will then open a query cursor
but only locking 1 row at a time. Before it processes each row, it will check to
see whether the row has been updated by checking that the update timestamp
is earlier than when the transaction was started. If its not, the program will
retrieve the old version of the row from the change table and process that
instead. Once the accounts have been generated, the global temporary table
can be dropped. One benefit of methodology 3 over that of Oracles rollback
segment solution, is that the change table can be indexed.
That said, Oracle 10gs undo tablespaces provide a significant advantage for
development/test environments as they allow the new flashback query/table
functionality to be used. Essentially, as undo information is held in an undo tablespace
for a time period controlled by the undo_retention system parameter, its possible to
query the state of a table at any given time during its retention history and also to
revert the table to its state at a particular time. Its not so useful for production
systems with high transaction rates as its unlikely that you could have a large enough
undo tablespace to retain records for a decent period of time.

14

8. Database scripting languages


The primary internal database scripting language for Oracle is still PL/SQL with
stored procedures also being able to be written in Java. Pro*C and OCI are the
primary external Oracle database scripting languages.
For DB2 - SQL/PL, Java and C are the primary internal database scripting languages.
SQL/PL does not have the concept of packages in terms of a collection of stored
procedures and Udfs. Oracle developers tend to make heavy use of package variables
allowing Oracle code in the same package to pass variables between different sections
very easily. However, the solution to this is to have the packages and package
variables in the application itself rather than inside the database code.
The primary DB2 scripting language is Java which has the advantage over PL/SQL of
being open source. DB2 also has Embedded SQL for C, which is very similar to
Pro*C

15

9. Database Monitoring
DB2 has event monitoring and snapshot monitoring.
DB2 event monitoring is usually used to capture deadlocks and sql statement
statistics. DB2 event analyser can be used to analyse the sql trace information.
DB2 snapshot monitoring can give point-in-time info about database manager,
database, tablespaces, bufferpools, tables, applications, locks and dynamic sql.
Many of the snapshots hold cumulative information which can be reset by typing
db2 reset monitor all
Up until v8, DB2 snapshot monitoring was only available as commands and produced
a listing style output. From v8 onwards, the statistics are now held in system tables
and can be queried as table functions from SQL, making it very similar to Oracle.
However, Oracle stores much more comprehensive system monitoring information
than DB2. For example, it stores cpu, memory and i/o information as well as a rolling
window of snapshots of sql sessions.
Oracle allows you to trace sql and analyse it using tkprof. You can monitor the
instance, database, tablespaces etc. by examing the v$ system views.
Since Oracle 8i, taking snapshots of information in these tables has been made easier.
The old way of running a bstat (before script) and estat (end script) was replaced by
the statspack in v9i. The statspack is a collection of packages and stored procedures
which allow you to monitor and retrieve snapshot statistics much more easily. Since
10g, the statspack have in turn been replaced by the automatic workload repository
(AWR).
Both Oracle 10g and DB2 9 have substantial autonomic statistics gathering and job
scheduling tools to simplify the life of a DBA.
Toad and Quest are 2 external vendors which specialise in snapshot monitoring of
Oracle, DB2 and SQL*Server.

16

10. DBA commands


1. Starting the database manager (instance)
Db2: db2start
Oracle: svrmgrl; startup
2. Shutting down the database manager (instance)
Db2: db2stop force
Oracle: svrmgrl; shutdown immediate
3. Connecting to a server
Db2: db2 connect to <db> user <user> identified by <password>
Oracle: sqlplus <user>/<password>@sid
4. Listing connected sessions
Db2: db2 list applications show detail
Oracle: select spid, osuser, s.program from v$process p, v$session s
where p.addr = s.paddr
5. Killing a selected session
DB2: db2 force application (application_id)
Oracle: orakill <sid> <spid>. alter system kill session <spid>, <session#>

17

6. Creating an instance
DB2: db2icrt $instance
Oracle: The manual method on windows is:a) copy an existing init.ora file and edit.
b) oradim -new -sid <sid> -intpwd <password> -startmode manual [-pfile
<path>/init<sid>.ora] (This creates all the instance-level services)
c) From command line, type set oracle_sid=<sid>
d) sqlplus /nolog
e) connect sys/<password> as sqldba
f) startup nomount
Note: If you get an ORA-03113 error, itll likely be due to memory problems. A
minimum init.ora file is:control_files = (c:\oracle\admin\ora10\control01.ora,
c:\oracle\admin\ora10\control02.ora,
c:\oracle\admin\ora10\control03.ora)
undo_management = auto
db_name
= ora10
db_block_size
= 8192

7. Creating a database
DB2: db2 create db <database name>. This takes under a minute.
Oracle:1. Firstly, you need to configure your oracle net services listener. The easiest way
to do this is by using the netca utility (If youre creating the database for the
first time on Windows and its not on a network, you also have to install a
Microsoft loopback adapter).
2. Then create the database. The easiest way is to use the database configuration
assistant utility - dbca - using an oracle-supplied template.
The manual alternative is comparatively complex. The steps are
a) Run the create database script, an example which is shown below:CREATE DATABASE ORA10
LOGFILE 'c:\oracle\admin\ORA10\logs\redo01.log'
SIZE 10M reuse,
'c:\oracle\admin\ORA10\logs\redo02.log'
SIZE 10M reuse,
'c:\oracle\admin\ORA10\logs\redo03.log'
SIZE 10M reuse,
'c:\oracle\admin\ORA10\logs\redo04.log'
SIZE 10M reuse
CHARACTER SET WE8ISO8859P1
NATIONAL CHARACTER SET UTF8
CONTROLFILE REUSE
DATAFILE 'c:\oracle\admin\ORA10\datafiles\system01.dbf'
SIZE 250M reuse
AUTOEXTEND ON
NEXT 10M MAXSIZE unlimited
EXTENT MANAGEMENT local
SYSAUX DATAFILE 'c:\oracle\admin\ORA10\datafiles\sysaux.dbf'
SIZE 50M reuse
AUTOEXTEND ON

18

NEXT 10M
MAXSIZE unlimited
UNDO TABLESPACE undo
DATAFILE 'c:\oracle\admin\ORA10\datafiles\undo.dbf'
SIZE 10M reuse
DEFAULT TEMPORARY TABLESPACE temp
TEMPFILE 'c:\oracle\admin\ORA10\datafiles\temp01.dbf'
SIZE 20M reuse;

Creating the database takes a similar time as it does to create a DB2 database, but
then you have to run the following 3 scripts to populate the catalog views,
indexes, functions, packages and stored procedures. These scripts take well over
an hour to complete.
b)
c)
d)
e)

@<admin>\catalog
@<admin>\catproc
Log in to sqlplus as system/<password>
@<admin>\pupbld

8. Dropping a database
DB2: db2 drop db <database name>
Oracle: drop database (new in Oracle 10g. Prior to this had to manually delete
files)
9. Turning on archive logging (hot backup)
DB2:
a) Compile the userexit db2uext2 and put in sqllib\bin directory
b) db2 update db cfg for <database> using logretain on
Oracle:
a) Edit the following init<sid>.ora parameters:i)
log_archive_start = true
ii)
log_archive_dest = "/apps/oracle/admin/o817/arch"
iii)
log_archive_format = arch_%t_%s.arc
b) Stop the instance
c) startup mount
d) alter database archivelog
e) alter database open
10. Determining current logfile sequence
DB2: db2 get db cfg for <database> and look at the First active log file
Oracle: archive log list and look at Current log sequence
11. Switching current logfile
DB2: archive log for database <database>
Oracle: alter system switch logfile
12. Backing up a database
DB2: online - db2 update db cfg using logretain on;
19

db2 backup db <database> online


offline - db2 force applications all;
db2 backup db <database>
Oracle:
For 10g, you should now use the following commands in the rman utility
online: alter database archivelog;
backup database plus archivelog delete input
offline: backup database
Note: The above statements connect to the database pointed to by $ORACLE_SID
and backup the database to the default location using a default level of parallelism.
13. Listing available backups
DB2: list backup all for $database
Oracle: list backup
14. Restoring a database
DB2:
online (to point in time)
a) db2 restore db <db> taken at <timestamp>
b) db2 rollforward db <db> to $point-in-time and complete
offline
a) db2 restore db <db> taken at <timestamp> without rolling forward
Oracle: Use the following rman utility commands:shutdown immediate
startup mount
Then use the following rman utility commands:online (to point in time)
restore database from tag=$tag
recover database until time to_date($point-in-time,YYYY-MMDD:HH24:MI:SS)
alter database open resetlogs;
offline restore database from tag=$tag
15. Exporting a table with its data
DB2: db2 export to <output file> of ixf select * from <source table>
Oracle: exp <username>/<password> file=<output file> tables=<source table>
16. Importing a table with its data
DB2: db2 import from <input file> of ixf create into <destination table>
Oracle: imp <username>/<password> file=<input file>
17. Creating a user
20

DB2: This is done via the operating system


Oracle: create user <user> identified by <password> default tablespace
<tablespace name> temporary tablespace <temp tablespace name>
18. Dropping a user
DB2: This is done via the operating system
Oracle: drop user <username>
19. Altering database and instance level configuration parameters
DB2: db2 update dbm cfg using $name $value. db2 update db cfg for $database
using $name $value. Instance level configuration parameters are stored in a file
called db2systm. Database configuration parameters in a file called sqldbcon
Oracle: alter system $name $value scope=both. Instance and database level
configuration parameters are held in spfile$SID.ora.
20. Displaying database and instance level configuration parameters
DB2: db2 get dbm cfg. db2 get db cfg for $database.
Oracle: select * from sys.v$spparameter
21. Displaying database name currently connected to
DB2: values (current server)
Oracle: select value from sys.v$spparameter where name = db_name
22. Displaying current timestamp
DB2: values (current timestamp)
Oracle: select to_char(systimestamp,YYYY-MM-DD-HH24.MI.SS.FF6) from
dual
23. Displaying an explain plan for a sql statement
DB2: db2expln -d $database -u $user $password -t -q $sql_stmt -g
Oracle: explain plan for $sql_stmt;
select * from table(dbms_xplan.display);
24. Displaying DDL for a table
DB2: describe table $schema.$tabname.
db2look -d $database -i $user -w $password -z $schema -t $table -e
Oracle: describe $schema.$tabname
select dbms_metadata.get_ddl($object_type,$object_name,$schema)
from dual
25. Gather statistics
DB2: runstats on table $schema.$table with distribution and detailed indexes all

21

Oracle: exec dbms_stats.gather_schema_stats(ownname=>'$schema',


options=>'gather auto', estimate_percent=>dbms_stats.auto_sample_size,
method_opt=>'for all columns size skewonly',degree=>15)
26. Reorganising table data within a tablespace
DB2: reorg table $schema.$table (can add suffix inplace to do online reorg
Oracle:
EXEC DBMS_REDEFINITION.CAN_REDEF_TABLE('scott', 'emp', 2);
2=rowid

--

CREATE TABLE emp_work AS SELECT * FROM emp WHERE 1=2;


EXEC DBMS_REDEFINITION.START_REDEF_TABLE('scott', 'emp', 'emp_work',
NULL, 2);
ALTER TABLE emp ADD PRIMARY KEY (empno);
EXEC DBMS_REDEFINITION.FINISH_REDEF_TABLE('scott', 'emp',
'emp_work');
DROP TABLE emp_work;

27. Listing all of Oracles packages


Oracle: select object_name from all_objects where object_type = PACKAGE;
Note: DB2 doesnt have a package, but a parent stored procedure with nested child
procedures duplicate a large amount of functionality which a DB2 package provides.
28. List the contents of an Oracle package
Oracle: describe $schema.$package
29. Describe a stored procedure
DB2: select text from syscat.procedures where procname = $procedure and
procschema = $schema
Oracle: select text from all_source where name=$procedure and owner =
$schema
30. How to catalog a remote server
DB2: You can either use the DB2 Configuration Assistant or Control Center or do
the manual method:catalog tcpip node $node remote $ip_address server $port.
catalog db $database at node $node
Oracle: You can either use Net Manger or Net Configuration Assistant or
Enterprise Manager or the manual method:You need to edit tnsnames.ora and add an entry:$database =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = $ip_address)(PORT = $port))
)

22

(CONNECT_DATA =
(SERVICE_NAME = $database)
)

You also need to ensure that you have an entry in listener.ora for the server:# listener.ora Network Configuration File:
C:\Oracle\product\10.2.0\db_1\NETWORK\ADMIN\listener.ora
# Generated by Oracle configuration tools.

LISTENER =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = $ip_address)(PORT = $port))
)

You will also need to recycle the listener:lsnrctl reload

Note: Oracle Net Services is undoubtedly one of Oracles weak areas. Configuring
Oracle for remote access is often seen more as an art than a science.
31. How to administer the database
DB2: Use DB2 Control Center (available when you install the Administration
Client).
Oracle: Use Oracle Enterprise Manager (the basic version of this comes with
Oracle 10g but if you want to administer remote servers you need to install the Oracle
Enterpise Manager 10g Grid Control). You really need at least 1Gb of memory to run
Enterprise Manager
To install the basic version, follow these steps:a) emca -repos create (Youll need to know the SID of the instance that you want
to control, the net services listener port and the password for sys) Creating the
repository takes about 15 minutes
b) emca -config -dbcontrol db. This again takes a few minutes to complete. At
the end , it will output a message telling you what the Database control url
is. Type this in to internet Explorer and youll be presented with the login
screen.
c) Once you accept the terms and conditions screen, you get in to Oracle
Enterprise Manager.
To start Oracle Enterprise Manager, after its installed type:a) emctl start dbconsole
It should be noted that Oracle Enterprise Manager is somewhat more extensive in
terms of functionality than the DB2 Control Center is, but DB2 Control Center is
much easier to setup/operate.
32. Creating a user
DB2: Use operating system commands to create a user and then log in to the
database and grant 1 or more of the following privileges to the user:23

grant connect, createtab on database to user $user (will allow the user to connect
and create tables)
grant use of tablespace $tablespace to user $user (will allow the user to create
objects in specified tablespace)
grant insert, update, delete, select on table $table to user $user (will allow the user
to insert, update, delete and select information from the specified table).
grant execute on procedure $procedure to user $user
grant execute on function $function to user $user
Note: DB2 by default grants implicit privileges to select from all tables to the
group public (in which all users are enroled). One of the first things a DB2 DBA
needs to do to make the database secure is to revoke the privileges assigned to group
public.
Oracle: create user $user identified by $password default tablespace
$user_tablespace temporary tablespace $temp_tablespace quota 2M on
$user_tablespace password expire
grant connect, resource to $user
grant all on $table to $user (will allow the user to insert, update, delete and select
information from the specified table)
grant execute on $function/$procedure to $user
33. Creating a group
DB2: Use operating system commands to create a group. DB2 administers groups
at different levels.
At the instance level, there are 4 special groups which are assigned using the update
dbm cfg $name using $value methodology. These groups are:sysadm_group - this is the highest authority. Allows a member of the group to do and
see everything in the database/instance
sysctrl_group - all the rights of a sysadm apart from not being able to alter the
instance level parameters and grant group privileges. Also doesnt allow direct access
to data.
sysmaint_group - all the rights of a sysctrl apart from cant create/drop a database or
tablespace or restore to a new database
sysmon_group - all the rights of a sysmaint apart from cant update database level
parameters, backup/restore a database, perform rollforward recovery or start and stop
an instance.
At the database level, there is a PUBLIC group to which all users belong. There is
also the dbadm privilege which is granted by using grant dbadm on database to user
$user. This privilege allows the user to create an event monitor, load data in to tables,
reorg and runstats the tables and prune log files, quiesce databases. dbadm can also
read all data in the database.
24

Finally, all of the grant privileges which Ive shown above for a user can be granted to
a group apart from those privileges for a stored procedure or function. DB2 allows
you to grant execute on a stored procedure or function to a group, but the users within
that group do not inherit the privilege which makes it redundant.
Oracle: Oracle calls groups - roles. Like DB2 roles get assigned privileges. In Oracle
10g, there are 173 system privileges which can be assigned to a role. You can find
these privileges by typing select name from system_privilege_map. The grouped
privileges / pre-defined roles most often granted to a user are connect (which allows
you to create session, alter session, create synonym, view, database link, table, index,
cluster, sequence) and resource (allows create table, index, cluster, sequence, trigger,
procedure, type). Theres also the dba role which combines the 2 above and allows the
user to grant privileges to other users.
34. Finding a users instance/system level privileges:DB2: Look at the sysadm, sysmaint, sysctrl & sysmon groups in the dbm cfg and
then check to see which users are in those groups at the o/s level.
Oracle:
select
lpad(' ', 2*level) || granted_role "User, his roles and privileges"
from
(
/* THE USERS */
select
null
grantee,
username granted_role
from
dba_users
where
username like upper('%&enter_username%')
/* THE ROLES TO ROLES RELATIONS */
union
select
grantee,
granted_role
from
dba_role_privs
/* THE ROLES TO PRIVILEGE RELATIONS */
union
select
grantee,
privilege
from

25

dba_sys_privs
)
start with grantee is null
connect by grantee = prior granted_role;

35. Finding a users object-level privileges.


DB2: First up, you need to check at the operating system level which groups a user is
in, then: select * from syscat.tabauth where grantee = $user and granteetype = U
union select * from syscat.tabauth where grantee in ($comma-seperated-groups-usersin) and granteetype = G
Oracle:
The following script shows what object privileges a particular user has:select
case when level = 1 then own || '.' || obj || ' (' || typ || ')'
else
lpad (' ', 2*(level-1)) || obj || nvl2 (typ, ' (' || typ || ')',
null)
end
from
(
/* THE OBJECTS */
select
null
p1,
null
p2,
object_name
obj,
owner
own,
object_type
typ
from
dba_objects
where
owner not in
('SYS', 'SYSTEM', 'WMSYS', 'SYSMAN','MDSYS','ORDSYS','XDB',
'WKSYS', 'EXFSYS',
'OLAPSYS', 'DBSNMP', 'DMSYS','CTXSYS','WK_TEST',
'ORDPLUGINS', 'OUTLN')
and object_type not in ('SYNONYM', 'INDEX')
/* THE OBJECT TO PRIVILEGE RELATIONS */
union
select
table_name p1,
owner
p2,
grantee,
grantee,
privilege
from

26

dba_tab_privs
/* THE ROLES TO ROLES/USERS RELATIONS */
union
select
granted_role p1,
granted_role p2,
grantee,
grantee,
null
from
dba_role_privs
)
start with p1 is null and p2 is null
connect by p1 = prior obj and p2 = prior own;

36. List table names:DB2: select tabschema, tabname from syscat.tables


Oracle: select * from sys.all_tables
37. List table columns:DB2: select colname from syscat.columns where tabschema = $schema and
tabname = $table
Oracle: select column_name from sys.all_tab_columns where owner = $schema
and table_name = $table
38. Describe a stored procedure:DB2: select text from syscat.procedures where procschema = $schema and
procname = $procedure
Oracle: select text from all_source where name = $procedure and owner =
$schema and type = PROCEDURE
39. Describe a user-defined function:DB2: select body from syscat.functions where funcschema = $schema and
funcname = $function
Oracle: select text from all_source where name = $function and owner =
$schema and type = FUNCTION
40. Creating a range partitioned table
DB2: create table partition by range ($range_key_column) (starting $start
ending $end every $time interval)
or
create table.partition by range ($range_key_column) (partition $partition1
starting $start1, partition $partition2 starting $start2 ending $end)
27

Oracle: create tablepartition by range ($range_key_column) (partition $partition


1 values less than ($end1) tablespace $tablespace1, partition $partition2 values
less than ($end2) tablespace $tablespace2)
41. Adding a partion to a range partitioned table
DB2: create table $partition constraint $constraint1 check
($partition_key_column between $start and $end).
alter table $table attach partition starting from $start ending at $end from
$partition.
Oracle: alter table $table add partition $partition
42. Dropping a partion from a range partitioned table
DB2: alter table $table detach partition $partition into $new_table
drop table $new_table
Oracle: alter table $table drop partition $partition
43. Emptying a table
DB2: import from /dev/null of del replace into $schema.$table
Oracle: truncate table $table;
44. Bufferpool hit ratio
DB2: select tablespace_name, bpname,
decimal(100*decimal(pool_index_l_reads+pool_data_l_reads)/(case when
pool_index_p_reads + pool_data_p_reads + pool_index_l_reads + pool_data_l_reads
= 0 then 1 else pool_index_p_reads + pool_data_p_reads + pool_index_l_reads +
pool_data_l_reads end),5,2) hit_ratio from table(snapshot_tbs(,-1)) as snap,
syscat.tablespaces tbs, syscat.bufferpools bp where tbs.bufferpoolid = bp.bufferpoolid
and snap.tablespace_name = tbs.tbspace (Youll need to issue db2 update dbm cfg
using dft_mon_bufpool on and recycle instance before to get results if
dft_mon_bufpool isnt already on).
Oracle:
SELECT NAME, PHYSICAL_READS, DB_BLOCK_GETS, CONSISTENT_GETS,
1 - (PHYSICAL_READS / (DB_BLOCK_GETS + CONSISTENT_GETS))
"Hit Ratio" FROM V$BUFFER_POOL_STATISTICS;

11. Main Differences


1. DB2 maintains its integrity by using lock isolation levels. It does not have
rollback segments/undo tablespace. This means that if a reader application tries to
28

read a row which has been updated, the reader application will be held in a lock wait
state until the writer application commits. Oracle manifests exactly the same
behaviour as DB2 if the Oracle developer opens a select for update cursor. DB2
reader applications can read the data without locking, if they use the Uncommited
Read isolation level. However, this level means that DB2 can read changed but
uncommitted data, whereas Oracle will read the data before it was changed. Oracles
approach does have a disadvantage in that if the writer application changes data which
the reader application is reading and then commits, the reader application will get a
snapshot too old error message. The other disadvantage of Oracles rollback
segments is it allows the developer to become lazy and commit transactions less often
than is desirable which can lead to performance issues. Various solutions to ensure
that concurrency problems dont occur with DB2 are presented in section 5 above. An
advantage of Oracles undo tablespace solution is that its possible to do flashback
querys to a previous point in time (provided the undo_retention period hasnt been
exceeded).
2. DB2s SQL/PL is compiled whereas Oracles PL/SQL is interpreted.
3. DB2s SQL/PL can only be used in stored procedure, Udf and triggers. It can not
be used as a standalone scripting language. This means, for example, that you cant
output information to the screen or to a file. You can, of course, insert that information
in to a table, however.
4. DB2 stored procedures can be written in C, Cobol and REXX in addition to
SQL/PL and Java. Oracles can only be written in PL/SQL and Java
5. There is no concept of a code package in DB2 SQL/PL. This has the disadvantage
that package variables cant be shared amongst a group of stored procedures. Again,
this can be circumvented by storing the package variables in the calling application.
6. With DB2 a single user can own multiple schemas whereas, in Oracle, a single
user owns a single schema.
7. DB2 v9 has introduced range partitioning but the previous versions didnt have
this. DB2 still doesnt have list partitioning. List partitioning is useful for certain
situations e.g. if you want to partition by countries in Europe or states in America.
DB2 and Oracle have hash partitioning, although in the case of DB2, you cant
partition a table, but have to partition the database, with each partition managed by a
separate DB2 instance. This does have the advantage, however, that more memory
can be used by DB2, as each database instance can address the maximum limit of the
operating system. DB2s partitioned edition (DB2 ESE with data partition facility
DPF) also has the advantage that it can be a shared nothing architecture. i.e. each
database partition can reside on its own disks and use its own cpu and memory.
Oracles Real Application Cluster (RAC) has to share the same data on the same
29

disks, which presents a potential bottleneck. An advantage of this, however, is that


you dont need to move data physically between partitions to ensure optimal
performance.
8. DB2 has had much simpler commands to create, monitor, backup, restore and
drop a database for a long time. However Oracle 10g, has simplified these tasks
greatly by using templates, incorporating automatic storage management and using
defaults so its becoming much better. Using Enterprise Manager wizards to do these
tasks also helps a lot.
9. DB2s optimiser is considered better than Oracle in deducing the most efficient
access plan. Oracle allows you to overrule the optimiser by using hints, however,
whereas, DB2 does not have this. The disadvantage of relying on hints is that they
only produce the most effective access plan for a known volume of data. Oracle has
another advantage in that you can lock statistics on volatile tables (thus preventing
them from being overwritten) and you can store multiple versions of the statistics, so
if you encounter a problem with a new set of stats, you can backtrack easily.
10. In DB2, users/groups are created in the operating system or specialist security
package and then grant privileges are assigned to them within the database. In
contrast, Oracle requires you to create users/group in the database itself and then
assign the grant privileges. Both Oracle 10g and DB2 9 allow for row-level security
to be implemented.
11. Storage characteristics are defined at the tablespace level in DB2. You can not
override them at the table/index level. This has the advantage that DB2 tablespaces
are less fragmented than Oracle and in busy systems theres no latch contention with
tables trying to extend their storage but the administrative disadvantage that objects
which have different storage characteristics require a separate tablespace. Since 10g,
Oracle now allows storage characteristics to be set at the tablespace level as well as
the table level, however, and uniform allocation of extents is also an option.
12. Theres no DB2 equivalent for Oracles net services listener In DB2, its listener
is started when the DB2 engine is brought up - Theres no separate service to be
started. You catalog remote servers and databases using standard DB2 commands or
the DB2 Configuration Assistant.With Oracle, you need to configure the listener.ora,
tnsnames.ora and sqlnet.ora files either manually or by using the Net Configuration
Assistant. The listener service is started and shutdown using the lsnrctl utility.
12. Oracles configuration parameters are either held in a readable form or in a
compiled form. When you startup oracle, you can tell it to read any file which has
configuration files in the correct format e.g. startup pfile=init.ora. This allows you to
have multiple versions of configuration files. You can dynamically allocate some
30

configuration parameters by using the alter system commands and you can make
these changes permanent by adding the scope=both or scope=spfile suffix.
You alter DB2s configuration parameters by running DB2 commands against the
instance-level parameters (db2 update dbm cfg) or database-level parameters (db2
update db cfg for $database.). Some further configuration parameters are held in
whats known as the DB2 registry. You can alter these by using the db2set command.

31

Potrebbero piacerti anche