2009년 3월 24일 화요일

hotbackup.sh

#!/bin/ksh
export ORACLE_HOME=/oracle/product/9.2.0
export ORACLE_OWNER=oracle
export ORACLE_SID=mcpay
. ${ORACLE_HOME}/.profile
_LOC=/usr/bin
_LOG=/backup/online_backup
_SRC=/backup/online_backup
_BCK=/backup/online_backup


DATE=`date +%y%m%d`




#########################################
######### Hotbackup Script Create ############
#########################################
#${_SRC}/cr_hotbackup.sh

$ORACLE_HOME/bin/sqlplus "/ as sysdba"<< EOF

set heading off
set echo off
set feedback off
set linesize 150
set pagesize 0
set long 10000

spool ${_SRC}/hotbackup_t1.sql
@${_SRC}/begin_backup
@${_SRC}/src.sql
@${_SRC}/end_backup
spool off

exit
EOF

${_LOC}/egrep -v '(SQL>)' ${_SRC}/hotbackup_t1.sql > ${_SRC}/hotbackup.sql

${_LOC}/rm ${_SRC}/hotbackup_t1.sql

#########################################
############ Hotbackup Exec ###############
#########################################
$ORACLE_HOME/bin/sqlplus "/ as sysdba"<< EOF

spool ${_LOG}/hotbackup_$DATE.log
@${_SRC}/hotbackup
alter system switch logfile;
alter database backup controlfile to '${_BCK}/backup_$DATE.ctl';
spool off

exit
EOF

#########################################
########### Archive log backup ##############
#########################################
${_SRC}/arc_del_make.sh

2009년 3월 22일 일요일

ORA-01102: cannot mount database in EXCLUSIVE mode

SQL> startup pfile='D:\oracle\ora92\database\initoracle.ora'
ORACLE instance started.

Total System Global Area 101784276 bytes
Fixed Size 453332 bytes
Variable Size 75497472 bytes
Database Buffers 25165824 bytes
Redo Buffers 667648 bytes
ORA-01102: cannot mount database in EXCLUSIVE mode



SQL> alter database mount
2 ;
alter database mount
*
ERROR at line 1:
ORA-01102: cannot mount database in EXCLUSIVE mode



--===================
리눅스의 경우 슈퍼유저(root)에서 ps -ef | grep ora를 해본뒤

오라클에 대한 프로세스가 있으면 kill -9 프로세스id 를 하거나

killall oracle을 하신뒤

다시 오라클 유저로 접속 후

startup 한다.



윈도우의 경우는

관리도구-> 서비스

oraclesid로 되어있는 서비스가 시작되어있는지 확인,

있으면 종료 후에 다시 시작한다.



[출처] ORA-01102 에러대처방법|작성자 곰탱

ORA-01089: immediate shutdown in progress - no operations are permitted

오라클 프로세스 강제 KILL 후 증상 [ ORA-01017 ]
환경 : Oracle 8i, AIX Unix
증상 : shut down/ 혹은 immediate 으로 down 중에 db가 정상적으로
내려가지 않는 사태가 발생하고, Unix kill(-9) command 를 통해서
강제로 오라클 백그라운드 프로세스를 종료 후에 디비를 재기동 하고자 하면,
아래와 같은 증상을 발견할 수 있다.
[ 테스트 장비 구축상황이었습니다. 라이브면 이러면 안되겠죠 ^^; 좀기다리세요 ]

>sqlplus ' / as sysdba'
SQL*Plus: Release 8.1.7.0.0 - Production on Sat Feb 4 19:23:58 2006
(c) Copyright 2000 Oracle Corporation. All rights reserved.
ERROR:
ORA-01089: immediate shutdown in progress - no operations are permitted
Enter user-name:
ERROR:
ORA-01017: invalid username/password; logon denied

이와같은 증상은 프로세스를 종료 되었으나, 오라클 관련 메모리가 아직 Clear 되지 않았을
때 있니다. 우선 아래와 같이 프로세스 및 메모리가 클리어 되었는지 확인 하세요.
ps -ef | grep oracle
ipcs -mb |grep oracle
m 2883616 0xbfd6e4b4 --rw-r----- oracle dba 358973440
ipcrm -m 2883616 [ 해당 메모리를 클리어 하기 ]
sqlplus ' / as sysdba'

SQL*Plus: Release 8.1.7.0.0 - Production on Sat Feb 4 20:07:11 2006

(c) Copyright 2000 Oracle Corporation. All rights reserved.

Connected to an idle instance.
정상 확인



##############################################################################

기타 명령어
:/ipms/dbwine> ipcs -sb | grep test
s 1441805 0x53006000 --ra-ra-ra- test dba 1
:/ipms/dbwine> ipcrm -s 1441805
:/ipms/dbwine> ipcs -sb | grep test

ipcs -qb | grep test

복구방법

복구방법

http://radiocom.kunsan.ac.kr
--------------------------------------------------------------------------------
갑작스런 시스템 장애나 사용자 실수 등으로 인하여 DB를 사용하지 못하게 되는 환경으로부터 사용자의 데이터를 관리하기 위해 백업을 통해 데이터를 저장한다. DB를 정상적으로 사용할 수 없게 된 경우, 백업된 파일을 사용하여 DB가 정상적으로 가동되도록 하는 작업을 복구(recovery)라 한다.
복구는 실제로 백업이라는 과정을 거처서만 이루어 지는 것이 아니다. 오라클 서버에 의해 DB 관리자가 모르는 사이 수시로 일어난다. 오라클 DB 서버가 시작할 때 리두 로그 파일을 참조하여 잘못된 내용이 있거나 복구할 내용이 존재하는 경우 자동으로 복구 작업이 시행된다.

복구 작업에 관련된 중요한 데이터 구조와 기능을 요약하면 다음과 같다.
데이터 구조 설명
제어 파일 DB의 물리적 구조에 대한 정보 유지/관리
시스템 변경번호(SCN) 오라클 DB의 커밋된 버전을 설명하는 값
DB의 시퀀스 생성기로 작동하며 동시성과 리두 레코드 순서 제어
리두 레코드 DB의 변경사항 하나를 설명하는 변경 벡터 그룹의 모든 데이터 블럭 변경 사항에 대해 작성되며, 디스크의 리두 로그에 저장
리두 로그 오라클 DB에 대한 모든 변경 사항 기록
DB를 복구할 때 리두 로그 사항 변경 사항을 데이터 파일에 적용
롤백 세그먼트 DB 복구 동안 리두 로그에서 데이터 파일에 적용된 커밋되지 않은 변경 사항을 실행 취소하는데 사용
백업 오라클 DB를 구성하는 물리적 파일의 운영체제 백업으로 구성
체크포인트 복구를 수행할 때 오라클이 올바른 시점에서 리두 응용 프로그램의 로그 스레드를 읽기 위해 사용



복구 방법은 아카이브 모드와 노아카이브 모드 두 가지 모드에서 가능하다.



--------------------------------------------------------------------------------
노아카이브 모드에서 복구
전체 DB에 대한 복구 작업은 노아카이브 모드에서만 적용할 수 있는 복구방법으로, DB에 문제가 발생한 시점을 기준으로 마지막 오프라인 백업된 데이터로 복구하는 방법이다. 그러나 이 방법은 마지막으로 백업된 시점부터 복구되기 때문에 백업이후부터 DB에 문제가 발생한 시점까지 변경된 내용은 전혀 복구할 수 없다.

노아카이브 모드의 특징은 다음과 같다.


• DB가 오프라인 되었을 때만 물리적인 백업이 가능하다.
• 모든 데이터 파일과 컨트롤 파일, 리두 로그 파일을 전부 백업해야 한다.
• 최종적으로 백업 받은 이후의 변경된 트랜젝션에 대한 내용은 복구할 수 없다.

다음 예제는 노아카이브 모드에서의 백업된 리두 로그 파일 없이 데이터베이스 복구의 예이다.
【예제】
1) 데이터베이스를 SHUTDOWN한다.
2) 가장 최근에 데이터베이스를 백업한 파일을 이용하여 복구작업을 수행한다.
3) 저장 위치가 변경된 데이터 파일들을 데이터베이스 서버가 인식할 수 있도록 컨트롤 파일을 수정하고
데이터베이스를 MOUNT 모드로 시작한다.
4) 저장 위치가 변경된 데이터 파일이 있으면 ALTER TABLESPACE 명령으로 데이터베이스 서버가 사용할 수 있게 한다.

ALTER TABLESPACE 테이블스페이스명 RENAME DATAFILE 원본파일이름 TO 새로운파일명

5) RESETLOGS 옵션을 사용하여 데이터베이스를 오픈한다. RESETLOGS 옵션은 불완전 복구를 하거나
REDO LOG FILE 없이 RESTORE했을 때 LOG SEQUENCE를 1로 되돌리고 시작하도록 한다.

ALTER DATABASE OPEN RESETLOGS;


--------------------------------------------------------------------------------
아카이브 모드에서 복구
아카이브 모드는 DB가 운영될 대에는 ARCH 프로세스가 리두 로그 파일을 순환적으로 덮어쓰기 전에 별도의 공간에 리두 로그 파일을 백업하여 이후 트랜젝션에 의해 변경된 데이터를 아카이브 로그 파일에 보관한다. DB를 아카이브 모드로 변경하려면 DB를 MOUNT할 때 아카이브 모드로 변환하는 명령을 수행해야 한다.
• 아카이브 모드에서는 아카이브 되지 않은 리두 로그 파일은 덮어쓰기를 하지 않는다.
• 아카이브 로그 파일은 일정기간 저장하기 위한 별도의 큰 공간이 필요하다.
• DB가 온라인 상태에서도 물리적인 백업이 가능하다.
• 물리적인 백업을 수행한 후에는 DB에 장애가 발생해도 장애 시점 이전까지 복구가 가능하다.
• 과거의 특정 시점으로 복구가 가능하다.
• DB가 온라인 상태인 경우에도 시스템 테이블스페이스를 제외한 특정 테이블스페이스나 데이터 파일의 복구가 가능하다.

아카이브 모드는 완전 복구와 불완전 복구 방법이 있다.
완전 복구는 데이터를 가지고 있어 문제가 발생한 시점까지 복구할 수 있는 방법으로 전체 데이터베이스, 테이블스페이스, 데이터 파일의 복구가 가능하다.

불완전 복구는 완전한 데이터를 가지고 있지 않아 데이터를 가지고 있는 시점까지만 복구하는 방법으로 취소기반 복구, 시간 기반 복구, 변경 기반 복구 방법이 있다.



--------------------------------------------------------------------------------
데이터베이스 전체를 완전 복구하기
이 방법은 노아카이브 모드에서 전체 DB 복구 작업이 최종 백업된 시점으로 돌아가는데 비해, DB에 문제가 발생한 시점까지 완전하게 복구하는 방법이다. 가장 먼저 해야할 일은 DB가 아카이브 모드인지 확인하는 것이다.

SQL> select log_mode from v$database;
SQL> archive log list;로 데이터베이스의 모드를 확인할 수 있다.


$ sqlplus system/manager as sysdba

SQL> select tablespace_name,file_name from dba_data_files;

TABLESPACE_NAME FILE_NAME
--------------- ------------------------------------------------------------
USERS /export/home/oracle/app/oracle/oradata/orcl/users01.dbf
SYSAUX /export/home/oracle/app/oracle/oradata/orcl/sysaux01.dbf
UNDOTBS1 /export/home/oracle/app/oracle/oradata/orcl/undotbs01.dbf
SYSTEM /export/home/oracle/app/oracle/oradata/orcl/system01.dbf

SQL>
SQL> select name from v$controlfile;

NAME
--------------------------------------------------------------------------------
/export/home/oracle/app/oracle/oradata/orcl/control01.ctl
/export/home/oracle/app/oracle/oradata/orcl/control02.ctl
/export/home/oracle/app/oracle/oradata/orcl/control03.ctl

SQL>
SQL> select group#,type,member from v$logfile;

GROUP# TYPE MEMBER
---------- ------- ------------------------------------------------------------
3 ONLINE /export/home/oracle/app/oracle/oradata/orcl/redo03.log
2 ONLINE /export/home/oracle/app/oracle/oradata/orcl/redo02.log
1 ONLINE /export/home/oracle/app/oracle/oradata/orcl/redo01.log

SQL>
SQL> !ls -l dbs/
total 60
-rw-r----- 1 oracle oinstall 1544 Jan 4 17:36 hc_orcl.dat
-rw-r--r-- 1 oracle oinstall 8384 Dec 4 13:14 init.ora
-rw-r--r-- 1 oracle oinstall 12920 Nov 22 07:13 initdw.ora
-rw-r----- 1 oracle oinstall 24 Jan 4 17:35 lkORCL
-rwSr----- 1 oracle oinstall 1536 Dec 30 10:46 orapworcl
-rw-r----- 1 oracle oinstall 2560 Jan 4 17:35 spfileorcl.ora

SQL>
SQL> Archive log list;
데이터베이스 로그 모드 아카이브 모드
자동 아카이브 사용
아카이브 대상 USE_DB_RECOVERY_FILE_DEST
가장 오래된 온라인 로그 순서 411
아카이브할 다음 로그 413
현재 로그 순서 413
SQL>
SQL> shutdown immediate;
데이터베이스가 닫혔습니다.
데이터베이스가 마운트 해제되었습니다.
ORACLE 인스턴스가 종료되었습니다.
SQL>
SQL> !
$ cp /export/home/oracle/app/oracle/oradata/orcl/*.dbf backup/
$ cp /export/home/oracle/app/oracle/oradata/orcl/*.ctl backup/
$ cp /export/home/oracle/app/oracle/oradata/orcl/*.log backup/
$ cp dbs/*.ora backup/
$ ls backup
control01.ctl init.ora redo02.log sysaux01.dbf undotbs01.dbf
control02.ctl initdw.ora redo03.log system01.dbf users01.dbf
control03.ctl redo01.log spfileorcl.ora temp01.dbf
$
$ rm /export/home/oracle/app/oracle/oradata/orcl/users01.dbf
$ cp backup/users01.dbf /export/home/oracle/app/oracle/oradata/orcl/users01.dbf
$ exit

SQL>
SQL> startup
SQL> drop user kim cascade;

사용자가 삭제되었습니다.

SQL> commit;

커밋이 완료되었습니다.

SQL> shutdown
데이터베이스가 닫혔습니다.
데이터베이스가 마운트 해제되었습니다.
ORACLE 인스턴스가 종료되었습니다.
SQL> !
$ cp backup/users01.dbf /export/home/oracle/app/oracle/oradata/orcl/users01.dbf
$ exit

SQL> startup mount;
ORACLE 인스턴스가 시작되었습니다.

Total System Global Area 289406976 bytes
Fixed Size 778796 bytes
Variable Size 99360212 bytes
Database Buffers 188743680 bytes
Redo Buffers 524288 bytes
Database mounted.

SQL> recover database;
매체 복구가 완료되었습니다.
SQL> alter database open;

데이타베이스가 변경되었습니다.

SQL>

다음과 같이 요약할 수 있다.
백업과정 복구과정 SQL> CONNECT system/manager AS SYSDBA
SQL> SHUTDOWN IMMEDIATE;
SQL> !
# cp *.dbf backup/*.dbf
# cp *.ctl backup/*.ctl
# cp *.log backup/*.log
# cp *.ora backup/*.ora
# rm user01.dbf
# cp backup/user01.dbf /export/home/oracle/app/oracle/oradata/orcl/users01.dbf
SQL> CONNECT system/manager AS SYSDBA
SQL> STARTUP MOUNT
SQL> RECOVER database;
SQL> ALTER database OPEN;



--------------------------------------------------------------------------------
테이블스페이스 완전 복구하기
전체 완전 복구방법은 파일을 사용할 수 없게 되었을 때 관련 파일들을 원래 경로에 복사하고, DB 전체를 복구하는 방법인데 비해, 테이블스페이스 완전 복구방법은 문제가 생긴 데이터 파일이 속한 특정 테이블스페이스만을 복구하는 방법이다. 이 방법은 문제가 생긴 테이블스페이스 이외의 다른 테이블스페이스들은 사용자에 의해 계속 사용될 수 있고 복구 시간을 줄일 수 있는 장점이 있다.
다음의 예는 테이블스페이스(user01.dbf)를 삭제한 경우라 가정하며, DB는 아카이브 모드이고 모든 파일이 백업된 상태라 하자.


$ sqlplus system/manager as sysdba
SQL> !

$ rm /export/home/oracle/app/oracle/oradata/orcl/users01.dbf
$ exit

SQL> shutdown immediate;
데이터베이스가 닫혔습니다.
데이터베이스가 마운트 해제되었습니다.
ORACLE 인스턴스가 종료되었습니다.

SQL> !
$ cp backup/users01.dbf /export/home/oracle/app/oracle/oradata/orcl/
$ exit

SQL>
SQL> startup mount
ORACLE instance started.

Total System Global Area 289406976 bytes
Fixed Size 778796 bytes
Variable Size 99360212 bytes
Database Buffers 188743680 bytes
Redo Buffers 524288 bytes
Database mounted.
SQL> alter database datafile
2 '/export/home/oracle/app/oracle/oradata/orcl/users01.dbf' offline;

Database altered.

SQL> alter database open;

Database altered.

SQL> alter tablespace users offline immediate;

Tablespace altered.

SQL> recover tablespace users;
ORA-00279: change 2982190 generated at 01/06/2006 13:16:36 needed for thread 1
ORA-00289: suggestion :
/export/home/oracle/app/oracle/flash_recovery_area/ORCL/archivelog/2006_01_06/o1
_mf_1_413_%u_.arc
ORA-00280: change 2982190 for thread 1 is in sequence #413


Specify log: {=suggested | filename | AUTO | CANCEL}

ORA-00279: change 2982873 generated at 01/06/2006 14:31:37 needed for thread 1
ORA-00289: suggestion :
/export/home/oracle/app/oracle/flash_recovery_area/ORCL/archivelog/2006_01_06/o1
_mf_1_414_%u_.arc
ORA-00280: change 2982873 for thread 1 is in sequence #414
ORA-00278: log file
'/export/home/oracle/app/oracle/flash_recovery_area/ORCL/archivelog/2006_01_06/o
1_mf_1_413_1vw05t11_.arc' no longer needed for this recovery


Specify log: {=suggested | filename | AUTO | CANCEL}

Log applied.
Media recovery complete.
SQL> alter tablespace users online;

Tablespace altered.

SQL>

다음과 같이 요약할 수 있다. 백업과정 복구과정
SQL> CONNECT system/manager AS SYSDBA
SQL> SHUTDOWN IMMEDIATE;
SQL> !
# cp *.dbf backup/*.dbf
# cp *.ctl backup/*.ctl
# cp *.log backup/*.log
# cp *.ora backup/*.ora

# rm user01.dbf
# cp backup/user01.dbf /export/home/oracle/app/oracle/oradata/orcl/users01.dbf
SQL> CONNECT system/manager AS SYSDBA
SQL> STARTUP MOUNT
SQL> alter database datafile
2 '/export/home/oracle/app/oracle/oradata/orcl/users01.dbf' offline;
SQL> alter database open;
SQL> alter tablespace users offline immediate;
SQL> recover tablespace users;
SQL> alter tablespace users online;






--------------------------------------------------------------------------------
데이터 파일 완전 복구하기
데이터 파일 완전 복구 방법은 하나의 데이터 파일이 하나의 테이블스페이스를 구성하는 경우, 하나의 데이터 파일 단위로 복구 작업을 수행 할 수 있도록 하는 방법이다. 데이터 파일 복구 방법 오프라인 또는 온라인 복구가 가능하다는 장점을 가지고 있으나, 시스템 데이터 파일은 데이터 파일 단위로 복구할 수 없고 불완전 복구가 안된다.


SQL> shutdown immediate;
Database closed.
Database dismounted.
ORACLE instance shut down.
SQL> host rm /export/home/oracle/app/oracle/oradata/orcl/users01.dbf

SQL> startup mount;
ORACLE instance started.

Total System Global Area 289406976 bytes
Fixed Size 778796 bytes
Variable Size 99360212 bytes
Database Buffers 188743680 bytes
Redo Buffers 524288 bytes
Database mounted.
SQL> alter database datafile
2 '/export/home/oracle/app/oracle/oradata/orcl/users01.dbf' offline;

Database altered.

SQL> alter database open;

Database altered.

SQL> recover datafile '/export/home/oracle/app/oracle/oradata/orcl/users01.dbf';
SQL>

다음과 같이 요약할 수 있다. 백업과정 복구과정
SQL> CONNECT system/manager AS SYSDBA
SQL> SHUTDOWN IMMEDIATE;
SQL> !
# cp *.dbf backup/*.dbf
# cp *.ctl backup/*.ctl
# cp *.log backup/*.log
# cp *.ora backup/*.ora

# rm user01.dbf
# cp backup/user01.dbf /export/home/oracle/app/oracle/oradata/orcl/users01.dbf
SQL> CONNECT system/manager AS SYSDBA
SQL> STARTUP MOUNT
SQL> alter database datafile
2 '/export/home/oracle/app/oracle/oradata/orcl/users01.dbf' offline;
SQL> alter database open;
SQL> recover tablespace users;
SQL> alter tablespace users online;





--------------------------------------------------------------------------------
불완전 복구
불완전 복구란 과거시점으로의 복구로서 데이터의 손실을 의미하는 것이기 때문에 불완전 복구를 결정하기 위해서는 매우 신중해야 한다. 불완전 복구를 하기 위해서는 전체 백업된 데이터 파일과 원하는 시점까지 아카이브 로그 파일이 모두 있어야 한다. 다음과 같은 경우 불완전 복구를 수행한다.


• 사용자가 다른 테이블을 삭제(drop)하여 논리적인 에러가 발생한 경우
• 잘못된 데이터가 DB에 commit되어 돌이킬 수 없을 경우
• 아카이브 로그 파일이 없어 완전 복구에 실패한 경우
• 모든 컨트롤 파일이 손상되어 컨트롤 파일을 새로 생성하는 경우
• 현재 사용중인 리두 로그 파일이 손상된 경우
• 백업된 컨트롤 파일을 사용하여 복구해야 하는 경우

불완전 복구 방법에는 시간기반(time based) 복구 방법, 취소 기반(cancel based) 복구 방법, 변경 기반(change based) 복구 방법 등이 있다.

--------------------------------------------------------------------------------
시간 기반 불완전 복구하기
시간 기반 복구 방법은 DB를 복구할 때 완전하게 복구하는 것이 아니라 특정 시간대까지만 복구하는 방법이다. 그러나 이 방법은 하나의 테이블을 복구하기 위해 해당 시간까지 모든 데이터를 복구해야 하는 단점이 있다.


진행과정
1) 현재 날짜와 시간을 확인한다.
SQL> host date;

2) 사용자 테이블을 살제한다.

SQL> DROP TABLE SCOTT.EMP;

3) 불완전 복구를 위해 DB를 종료하고, 모든 데이터베이스 파일을 복사하자

SQL> SHUTDOWN IMMEDIATE;
SQL> HOST cp /export/home/oracle/app/oracle/oradata/orcl/*.dbf backup/

4) DB를 MOUNT 단계로 시작하자.

SQL> STARTUP MOUNT PFILE=dbs/pfile.ora

5) RECOVER DATABASE UNTIL TIME 명령어를 사용하여 EMP 테이블이 삭제되기 전의 시간까지
데이터베이스 전체를 복구한다.

SQL> RECOVER DATABASE UNTIL TIME 'jan/07/2006 10:25:10';

6) DB를 OPEN하자. 이때 주의할 점은 불완전 복구 방법을 사용하여 DB를 복구하려면
ALTER DATABASE OPEN RESETLOGS 명령어를 사용해야 한다는 것이다.
ALTER DATABASE OPEN RESETLOGS 명령어를 사용하면
모든 시스템 변경번호, 로그 시퀀스 번호 등의 값을 0으로 초기화 시켜 오픈하게 된다.

SQL> ALTER DATABASE OPEN RESETLOGS;

7) 이제 BMP 테이블을 조회해 본다.


--------------------------------------------------------------------------------
취소 기반 불완전 복구하기
아카이브 모드의 DB를 사용하다 보면 아카이브 파일이 너무 많이 생성되고, 이런 아카이브 파일에 문제가 생겨 완전 복구 작업을 수행하지 못하는 경우가 생긴다. 이런 경우 적용 가능한 아카이브 파일까지만 복구되도록 할 수 있는데, 이 복구 방법을 취소 기반 복구방법이라 한다.

다음의 예는
DB는 아카이브 모드이고, 오프라인 백업 방법으로, 모든 데이터 파일을 백업해둔 상태라 하자. 그 후 사용자가 데이터를 변경하였고 LGWR 백그라운드 프로세스에 의해 변경된 정보는 백업되었고, 그 변경된 데이터는 아카이브 파일에 저장되었다. 이때 사용자가 실수로 user01.dbf파일과 arc3.log 아카이브 파일을 삭제했다고 가정해 보자.


진행과정
1) 먼저 DB를 종료하고, 데이터 파일 user01.dbf과 아카이브 파일을 삭제하자.

SQL> SHUTDOWN IMMEDIATE;
SQL> HOST rm /export/home/oracle/app/oracle/oradata/orcl/user01.dbf
SQL> HOST rm /export/home/oracle/app/oracle/oradata/orcl/arc3.log

2) 불완전 복구를 위해 모든 DB 파일을 복사한다.

SQL> HOST cp backup/*.dbf /export/home/oracle/app/oracle/oradata/orcl/

3) 이제 다시 DB를 MOUNT 단계에서부터 시작하자.

SQL> STARTUP MOUNT PFILE=dbs/pfile.ora

4) RECOVER DATABASE UNTIL CANCEL 명령어를 사용하여 취소 기반 복구 방법을 실행하자.
적용해야할 아카이브 파일이 존재하면 오라클 서버는 ORA-00279메시지와 함께 적용할
아카이브 파일명을 화면에 표시한다.

SQL> RECOVER DATABASE UNTIL CANCEL;

화면에 표시된 파일명에 4 가지 조건중 하나를 선택하면 된다.
[RET=suggest]는 ORA-00279 코드와 함께 출력된 아카이브 파일을 통해 복구를 실행하고,
[filename] 옵션은 DB 관리자가 직접 아카이브 파일의 경로와 파일명을 지정할 수 있다.
[AUTO] 옵션은 적용해야할 아카이브 파일을 오라클 서버가 선택하여 적용하고,
[CANCEL] 옵션은 지정된 아카이브 파일을 더 이상 적용하지 않는다.

5) RESETLOGS 옵션을 사용하여 DB를 오픈한다.

SQL> ALTER DATABASE OPEN RESETLOGS;


--------------------------------------------------------------------------------
변경 기반 불완전 복구하기
변경 기반 불완전 복구 방법은 주로 분산 DB 환경에서 사용하는 방법이다. 분산 DB 환경이란 하나의 네트워크 환경에서 여러 개의 DB를 설치하여 사용하는 환경으로 각각 별도의 DB가 구축되어 있으나 데이터들은 서로 밀접하게 연결되어 있다.
예를 들어, A 서버와 B 서버를 사용하는 환경에서 갑작스런 정전과 같은 이유 때문에 A 서버에 문제가 발생하여 복구 작업을 수행했다고 가정해 보자. 이때 복구된 A 서버와 C 서버 사이의 데이터가 불일치할 수 있는데, 이런 경우 DB에 저장되어 있는 각 시점별 시스템 변경번호(SCN)를 확인하여 같은 시점으로 복구하는데, 이러한 방법을 변경 기반 복구라 한다.


진행방법
1) DB에 접속하고 UPDATE 문을 사용하여 데이터를 변경하고 커밋을 한다. 커밋하면
시스템변경번호가 발행된다.

SQL> UPDATE SCOTT.EMP SET SAL=SAL*1.1;

2) ALTER SYSTEM SWITCH LOGFILE 명령어를 사용하여 로그 스위치가 발생하면 관련된 시스템 변경번호(SCN)가 데이터 사전에 저장된다.

SQL> ALTER SYSTEM SWITCH LOGFILE;

시스템 변경번호(SCN)에 대한 정보는 V$LOG_HISTORY 뷰를 사용하여 확인한다.

3) 변경 기반 복구 방법을 실행하기 위해 먼저 DB를 종료하고, USERS01.DBF 파일을 삭제하자.

SQL> SHUTDOWN IMMEDIATE
SQL> HOST rm /export/home/oracle/app/oracle/oradata/orcl/users01.dbf

4) 불완전 복구 작업을 위해 이전의 최종 오프라인 백업 정보 중에서 데이터 파일을 복사한다.

SQL> HOST cp backup/*.dbf /export/home/oracle/app/oracle/oradata/orcl/

5) DB를 다시 시작한다.

SQL> STARTUP PFILE=dbs/init.ora

6) V$LOG_HISTORY 뷰를 통해 확인한 시스템 변경번호까지 불완전 복구를 수행하고
DB를 RESETLOGS 옵션으로 오픈한다.

SQL> RECOVER DATABASE UNTIL CHANGE 889835;
SQL> ALTER DATABASE OPEN RESETLOGS;



--------------------------------------------------------------------------------
RMAN를 이용한 백업과 복구
Recovery manager는 오라클 DB의 백업과 복구에 관련된 정보를 저장하고, 필요한 경우에 백업과 복구를 수행하는 유틸리티이다. 복구 메니저는 오라클 엔터프라이즈의 GUI나 RMAN 명령어를 수행하여 사용할 수 있다.
복구 매니저는 다음과 같은 순서로 실행한다.


1) rman 사용자 프로세스 시작
2) 타킷 데이터베이스에 접속할 서버 프로세스 생성
3) 디스크나 테이프등에 쓰기 위한 프로세스 추가 생성
4) 복구 카탈로그 DB에 접속(선택적)

복구 매니저의 구성 요소와 기능은 다음과 같다.
구성 요소 설 명
타킷 데이터베이스 백업될 테이블과 데이터 파일을 가진 대상 DB
카탈로그 DB 타킷 DB에 대한 백업과 복구 관련 정보를 저장하는 DB
복구매니저 타킷 DB에 대한 백업과 복구 정보를 카탈로그 DB에 저장하고, 백업과 복구를 실행할 수 있는 환경 제공
채널 복구 매니저에 의해 백업과 복구 작업 실행시 테이블스페이스의 백업장치간의 작업을 처리해주는 서버 프로세스
기타 프로세스 각 구성요소를 사용하기 위한 서버 프로세스
DEFAULT, RCVCAT, ROLLING


복구 매니저 기능 기능 세부 기능
다양한 백업 방법 지원 • DB 전체 백업
• 테이블스페이스 단위 백업
• 데이터 파일 단위 백업
인크리멘털 백업지원 • 이전 백업이후 변경된 부분만 백업 가능
• 백업시간 최소화
• 백업중 발생 요인 최소화
병렬 백업 지원 한 번에 여러 백업 테이프 데이터 파일 백업 가능
백업과 복원 동시 수행 오라클 병렬 시스템의 경우 특정 데이터 파일에 대한 백업을 다른 데이터 파일의 복원을 위해 사용 가능
로그 기능 • 백업과 복구에 대한 정보제공
• 오류 분석에 이용
자동화 기능 • 테이프 복구 등을 자동으로 수행
• 반복 작업 쉽게 수행
• 백업작업 수행시간 지정 가능
다양한 사용자 인터페이스 지원 • 라인 에디터: RMAN
• GUI : 오라클 엔터프라이즈 매니저에서 이용가능
타킷 DB 관리 백업과 복구의 대상인 DB의 시작(startup)과 종료(shutdown)





--------------------------------------------------------------------------------
환경 설정하기
오라클 DB를 설치하면 기본적으로 복구매니저 기능을 사용할 수 없다. 복구 매니저의 기능을 사용하려면 카탈로그 DB를 만들어야 하는데, 카탈로그 DB는 복구 대상인 타킷 DB와 분리되어 관리해야 한다. 그 이유는 복구 대상인 DB와 동시에 문제가 발생하는 상황을 최소화 하기 위해서이다.

카탈로그 DB를 생성하는 경우 기본적인 테이블스페이스 크기와 이름을 고려하여 생성하여야 하며, 기본 환경을 설정한 후 DB에 접속하기 위한 사용자의 계정과 암호 그리고 관련 패키지( DBMS_BACKUP_RESTORE, DBMS_RCVCAT, DBMS_RCVMAN)및 데이터 사전을 생성해야 한다.

카탈로그 스키마 생성하기


1) 관리자 권한으로 접속한다.

SQL> conn sysstem/manager as sysdba

2) 카탈로그 DB를 사용할 사용자와 스키마를 생성한다.
SQL> create tablespace temp_rm
2 datafile 'rman.dbf' size 10m;

SQL> create user rman identified by rman
2 temporary tablespace temp
3 default tablespace cattbs
4 quota unlimited on cattbs;

3) rman 사용자에게 RECOVERY_CATALOG_OWNER 역할과 필요한 권한을 부여한다.

SQL> GRANT RECOVERY_CATALOG_OWNER TO rman;
SQL> GRANT CONNECT, RESOURCE TO rman;

카탈로그 DB 사용자를 생성한 후에 CREATE CATALOG 명령문을 사용하여 카탈로그를 생성해야 한다.
카탈로그 DB 생성하기


1) 운영체제에서 rman 유틸리티를 사용하여 DB에 접속한다.

# rman CATALOG rman/rman

2) CREATE CATALOG 명령문을 사용하여 카탈로그 DB를 생성한다.

rman> CREATE CATALOG;

RMAN 사용자를 생성할 때 DEFAULT TABLESPACE 절을 정의하지 않는 경우라면 다음과 같이 입력한다.

rman> CREATE CATALOG TABLESPACE rman_tbs;

3) 관련된 패키지(DBMS_BACKUP_RESTORE, DBMS_RCVCAT, DBMS_RCVMAN)를 생성한다.


--------------------------------------------------------------------------------
타킷 DB에 등록하기
이제 rman 명령어를 사용하여 DB에 접속하는 방법을 살펴보자
카탈로그 DB 생성하기


1) 타켓 DB와 카탈로그 DB에 접속하기 위해 다음과 같이 입력한다.

# rman TARGET 'sys/change_on_install as sysdba' CATALOG rman/rman

2) 복구 매니저를 사용하여 카탈로그 DB에 저장할 타킷 DB에 대한 정보를 등록한다. 이 명령어는
복구 매니저 설치 후 한 번만 하면 된다.

rman> REGISTER DATABASE;

3) 정보 등록이 성공적으로 이루어 졌는지 REPORT SCHEMA 명령으로 확인한다.

rman> REPORT SCHEMA;


--------------------------------------------------------------------------------
RMAN을 사용하여 백업하기
이제 rman 유틸리티를 사용하여 백업하는 과정을 보자.

DB 파일과 아카이브 파일 백업하기
DB가 마운트되거나 오픈되었을 때 rman 유틸리티의 backup 명령어를 사용하여 다음 객체를 백업할 수 있다.


• 데이터베이스
• 테이블스페이스
• 데이터 파일
• 아카이브 리두 로그 파일
• 컨트롤 파일

rman 유틸리티에서 백업할 때 사용하는 명령어와 옵션은 다음과 같다.


BACKUP [백업타입][옵션]

여기서 백업 타입은 다음과 같다.
백업 타입 설 명
database DB 전체 백업
tablespace 테이블스페이스명 특정 테이블스페이스만 백업
datafile 파일명 특정 데이터파일만 백업
datafilecopy 파일명 특정 데이터파일을 복사하여 백업
archivelog all 백업시 모든 아카이브 파일 백업
current controlfile 백업시 현재 컨트롤 파일 백업
controlfilecopy 파일명 백업시 현재 컨트롤 파일을 복사하여 백업


옵션의 종류는 다음과 같다.
옵션 설 명
TAG='내용' 현재 백업 절차에 대한 주석
FILESPERSET=n 백업 조각의 수
DELETE INPUT 백업 후 아카이브 파일 삭제
FORMAT='파일경로와 파일명' 백업 파일경로와 파일명
%P 백업 세트내의 백업 조각 번호
%S 백업 세트 번호
%D 타킷 DB 이름
%N 타킷 DB의 다른 표시 이름
%T 초단위 시간 정보
%U 백업세트와 시간 정보로 만든 8문자



rman을 사용하여 백업작업을 수행하는 경우 여러 개의 데이터 파일, 아카이브 파일, 컨트롤 파일등을 사용자가 지정하는 개수로 백업할 수 있는데, 이를 백업 세트라 한다. 또한 하나의 백업 세트 안에 저장될 수 있는 파일의 개수를 백업 조각(backup piece)라 한다.

v$backup_set 뷰를 참조하여 현재 생성되어 있는 백업세트의 개수와 각 백업 세트의 블럭 크기를 조회할 수 있다.
v$backup_piece 뷰를 통해서 생성된 백업세트의 경로와 파일명을 알 수 있다.


SQL> SELECT RECID,BLOCK_SIZE FROM V$BACKUP_SET;

SQL> SELECT RECID,SET_COUNT,PIECE#, HANDLE FROM V$BACKUP_PIECE;


--------------------------------------------------------------------------------
RMAN을 사용하여 복구하기
rman 유틸리티를 사용하더라도 기본적인 DB 복구 방법은 복구 매니저를 사용하지 않는 경우와 동일한 절차로 실행된다. 복구 매니저는 백업한 데이터 파일이나 정보등을 사용하여 DB나 테이블스페이스, 데이터 파일 등을 복구 할 수 있는데, 반드시 복구 대상인 DB의 컨트롤 파일과 카탈로그 DB를 사용할 수 있어야 한다.

rman에서 사용하는 복구 명령어는 다음과 같다.

RESTORE [restore_type][옵션]
RECOVER [restore_type][옵션]

여기서 restore_type은 다음과 같다.
restore_type 설 명
DATABASE 백업된 전체 데이터를 타킷 DB로 복사
TABLESPACE 특정 테이블스페이스의 데이터 파일만 복사
DATAFILE '파일이름' 특정 데이터 파일만 복사
ARCHIVELOG ALL 아카이브로그 파일을 복사
CONTROLFILE TO '경로' 지정 위치에 컨트롤 파일 복사


옵션은 다음과 같다.



[FROM TAG='내용'] 복구 작업에 대한 주석 작성


--------------------------------------------------------------------------------
RMAN을 사용하여 전체 복구하기
전체 복구는 아카이브/노아카이브 모드에 관계없이 가능하며, 노아카이브 모드인 경우는 최종 백업된 파일을 복사하고,
아카이브 모드인 경우에는 아카이브 파일을 적용하여 완전 복구한다.

전체 복구 진행 과정

1) rman으로 타킷 DB에 접속하고 마운트 단계로 DB를 시작한다.

# rman TARGET 'sys/change_on_install as sysdba'
rman> STARTUP MOUNT;

2) 복구 매니저에 의해 Db 전체 백업 데이터를 타킷 DB로 복사한다.

rman> RESTORE DATABASE;

3) 복사된 백업 데이터를 복구한다.

rman> RECOVER DATABASE;

4) 타킷 DB를 일반 사용자가 참조할 수 있도록 하고, 카탈로그 DB를 초기화 시킨다.

rman> ALTER DATABASE OPEN;


--------------------------------------------------------------------------------
RMAN을 사용하여 테이블스페이스 복구하기
테이블스페이스를 복구하기 위해서는 RESTORE와 RECOVER 명령어에 복구할 테이블스페이스를 정의하면 복구 매니저에 의해 복구 작업이 완료된다.
테이블스페이스 복구 작업은 DB를 사용하는 도중에 수행할 수 있는 방법이기 때문에 해당 테이블스페이스를 오프라인으로 하여 복구 작업을 수행한 후 온라인으로 변경해주어야 한다.


rman> RUN{
SET UNTIL TIME='2006-01-20:15:25';
ALTER DATABASE MOUNT;
RESTORE DATABASE;
RECOVER DATABASE;
sql 'ALTER DATABASE OPEN RESETLOGS';
}

백업방법

백업방법

http://radiocom.kunsan.ac.kr
--------------------------------------------------------------------------------
오라클 DB 백업은 1)물리적 백업(physical backup)과, 2)논리적 백업(Logical backup)의 두가지 방법이 있다.

--------------------------------------------------------------------------------
물리적 백업
물리적인 백업은 데이터베이스 파일(데이터 파일, 컨트롤 파일)을 백업하는 것을 뜻하며, DB가 아카이브 모드에서 수행중인 경우에는 아카이브 리두 로그 파일이 자동적으로 생성되므로 데이터 파일, 컨트롤 파일, 아카이브 리두 로그 파일이 백업된다.
물리적 백업은 다음과 같이 두 가지가 가능하다.


• 오프라인 백업
• 온라인 백업


--------------------------------------------------------------------------------
오프라인 백업
Off-line backup은 테이블스페이스나 데이터 파일이 오프라인일 때 실행되는 백업으로, 가장 수행하기 쉬운 백업방법중의 하나이다. 오프라인 백업은 DB를 종료하고, Db와 관련된 모든 물리적인 파일(데이터 파일, 컨트롤 파일, 매개변수 파일)을 운영체제 명령어를 이용하여 복사한다.
이 백업은 데이터 파일의 크기가 매우 큰 경우, 많은 시간이 소요될 수 도 있다. 그래서 오프라인 백업을 whole-backup 또는 cold-backup이라 한다.


$ sqlplus system/manager as sysdba ☜ DBA로 접속

SQL> select name from v$controlfile; ☜ 컨트롤 파일의 위치를 확인

NAME
--------------------------------------------------------------------------------
/export/home/oracle/app/oracle/oradata/orcl/control01.ctl
/export/home/oracle/app/oracle/oradata/orcl/control02.ctl
/export/home/oracle/app/oracle/oradata/orcl/control03.ctl

SQL> select file_name from dba_data_files; ☜ 데이터 파일의 확인

FILE_NAME
--------------------------------------------------------------------------------
/export/home/oracle/app/oracle/oradata/orcl/users01.dbf
/export/home/oracle/app/oracle/oradata/orcl/sysaux01.dbf
/export/home/oracle/app/oracle/oradata/orcl/undotbs01.dbf
/export/home/oracle/app/oracle/oradata/orcl/system01.dbf

SQL> select group#,member from v$logfile; ☜ 리두 로그 파일을 확인

GROUP# MEMBER
---------- ------------------------------------------------------------
3 /export/home/oracle/app/oracle/oradata/orcl/redo03.log
2 /export/home/oracle/app/oracle/oradata/orcl/redo02.log
1 /export/home/oracle/app/oracle/oradata/orcl/redo01.log

SQL>
SQL> shutdown normal; ☜ normal, transaction, immediate중 하나로 DB를 종료
Database closed.
Database dismounted.
ORACLE instance shut down.
SQL> ! ☜ 쉘 프롬프트로 일시 복귀함
$ su ☜ root의 권한을 가짐
Password:
# cp /export/home/oracle/app/oracle/oradata/orcl/control0*.ctl /export/home/work/. ☜ 컨트롤 파일 복사
# cp /export/home/oracle/app/oracle/oradata/orcl/redo*.log /export/home/work/. ☜ 리두 로그 파일 복사
# cp /export/home/oracle/app/oracle/oradata/orcl/*.dbf /export/home/work/. ☜ 데이터 파일 복사
# cp dbs/*.ora /export/home/work/. ☜ 파라미터 파일 복사
# ls -l /export/home/work ☜ 복사되었나 확인
-rw-r----- 1 root other 2867200 Jan 4 11:07 control01.ctl
-rw-r----- 1 root other 2867200 Jan 4 11:07 control02.ctl
-rw-r----- 1 root other 2867200 Jan 4 11:07 control03.ctl
-rw-r--r-- 1 root other 8384 Jan 4 11:14 init.ora
-rw-r--r-- 1 root other 12920 Jan 4 11:14 initdw.ora
-rw-r----- 1 root other 10486272 Jan 4 11:09 redo01.log
-rw-r----- 1 root other 10486272 Jan 4 11:09 redo02.log
-rw-r----- 1 root other 10486272 Jan 4 11:09 redo03.log
-rw-r----- 1 root other 2560 Jan 4 11:14 spfileorcl.ora
-rw-r----- 1 root other 461381632 Jan 4 11:10 sysaux01.dbf
-rw-r----- 1 root other 471867392 Jan 4 11:11 system01.dbf
-rw-r----- 1 root other 20979712 Jan 4 11:11 temp01.dbf
-rw-r----- 1 root other 26222592 Jan 4 11:11 undotbs01.dbf
-rw-r----- 1 root other 5251072 Jan 4 11:11 users01.dbf

# exit ☜ root 권한에서 빠져나옴
$ exit ☜ 쉘프롬프트에서 오라클 프롬프트로 복귀

SQL> startup ☜ Instance 기동
ORACLE instance started.

Total System Global Area 289406976 bytes
Fixed Size 778796 bytes
Variable Size 99360212 bytes
Database Buffers 188743680 bytes
Redo Buffers 524288 bytes
Database mounted.
Database opened.
SQL>


--------------------------------------------------------------------------------
자동으로 오프라인 백업실행하기
오프라인 백업은 데이터 파일의 크기가 작은 경우 쉽고, 간단하게 실행할 수 있지만, 데이터 파일이 큰 경우는 많은 시간이 소요되므로 스크립트를 사용하여 운영체제의 스케듈러에 의해 백업이 자동으로 실행되도록 할 수 있다.

다음과 같이 오프라인 자동 백업 스크립트를 작성하여 실행한다.

1단계 : 오라클 인스턴스 종료
$ORACLE_HOME/bin/sqlplus system/manager as sysdba
SHUTDOWN IMMEDIATE
EXIT

2단계 : 데이터베이스와 관련된 모든 물리적 파일 복사
cp /export/home/oracle/app/oracle/oradata/orcl/*.ctl backup/
cp /export/home/oracle/app/oracle/oradata/orcl/*.dbf backup/
cp /export/home/oracle/app/oracle/oradata/orcl/*.log backup/
cp /export/home/oracle/app/oracle/oradata/orcl/*.ora backup/

3단계 : 데이터베이스 다시 시작
$ORACLE_HOME/bin/sqlplus system/manager as sysdba
STARTUP
EXIT
EOF


--------------------------------------------------------------------------------
온라인 백업
오프라인 백업이 DB가 종료한 상태에서 백업하는 것에 반해, 온라인 백업은 DB를 운영하는 도중에 백업을 실행하는 방법이다. 온라인 백업은 테이블스페이스 단위로 백업을 수행하며 ALTER TABLESPACE 명령으로 테이블스페이스를 백업모드로 설정하고, 데이터 파일을 운영체제에 복사한다.
온라인 백업을 hot backup 또는 open backup이라 한다. 온라인 백업은 오프라인 백업과 달리 모든 파일을 백업할 수 없고, 필요한 테이블스페이스만 백업할 수 있다.

$ sqlplus '/as sysdba'
SQL> select tablespace_name, file_name from dba_data_files;

TABLESPACE_NAME FILE_NAME
--------------- ------------------------------------------------------------
USERS /export/home/oracle/app/oracle/oradata/orcl/users01.dbf
SYSAUX /export/home/oracle/app/oracle/oradata/orcl/sysaux01.dbf
UNDOTBS1 /export/home/oracle/app/oracle/oradata/orcl/undotbs01.dbf
SYSTEM /export/home/oracle/app/oracle/oradata/orcl/system01.dbf

SQL> alter tablespace users begin backup;
☜ 테이블스페이스내의 모든 객체에 대해 변경된 데이터들이 데이터 파일에 적용되고, 메모리 영역과 리두 로그 파일에 일시적으로 저장된다.

Tablespace altered.

SQL> !
$ cp /export/home/oracle/app/oracle/oradata/orcl/users01.dbf bkup/.
$ ls -l bkup
total 10272
-rw-r----- 1 oracle oinstall 5251072 Jan 4 14:07 users01.dbf
$ exit

SQL> alter tablespace users end backup;
☜ 복사후 sql문을 실행하여 데이터파일에 저장되었던 변경된 데이터를 실제 데이터 파일에 반영한다.

Tablespace altered.

SQL>
SQL> ALTER SYSTEM SWITCH LOGFILE;
☜ 인위적으로 로그 스위치를 실행하여 모든 데이터 파일 헤더에 저장되어 있는 체크포인트 번호를 통합

System altered.

SQL>


--------------------------------------------------------------------------------
논리적 백업
논리적 백업은 DB내의 논리적 객체들을 백업하는 방법으로, EXPORT 유틸리티를 사용하여 백업하고, IMPORT 유틸리티를 사용하여 복구한다.
EXPORT와 IMPORT 유틸리티가 백업/복구 이외에 다른 기능은 다음과 같다.


• 특정 사용자의 객체를 다른 사용자의 공간으로 이동시킬 수 있다.
• 운영체제가 다른 DB 사이에 데이터를 이동시킬 수 있다.
• 테이블, 뷰,인덱스 등을 백업하고 다시 복구함으로써 객체들의 구조가 재생성되어
단편화(fragmentation)를 감소시킨다.

익스포트에서 사용 가능한 키워드는 EXP 유틸리티를 참조하고
또한 익스포트를 사용하여 논리적으로 DB를 백업하는 방법은 데이터 베이스 전체모드, 테이블스페이스 모드, 사용자모드, 테이블모드의 4 종류가 있다.
데이터베이스 전체모드
•모든 테이블의 데이터
•인덱스
•테이블의 제약조건
•트리거
•클러스트
•시퀀스
•스냅샷
•스토어드 프로시저
•시노늄
•뷰
•프로파일/롤
•audit •지정된 테이블스페이스의 테이블

테이블스페이스 모드
•테이블의 데이터
•인덱스
•테이블의 제약조건
•트리거
•클러스트
•시퀀스
•스냅샷
•스토어드 프로시저
•시노늄
•뷰
•프로파일/롤
•audit •정의된 사용자의 테이블

사용자 모드
•테이블의 데이터
•사용자의 권한
•사용자의 인덱스
•테이블의 제약조건
•테이블의 트리거
•클러스트
•데이터베이스 링크
•스냅샷
•스토어드 프로시저
•시노늄
•뷰

테이블 모드
•정의된 사용자의 테이블
•테이블의 데이터
•사용자의 권한
•사용자의 인덱스
•테이블의 제약조건
•트리거





--------------------------------------------------------------------------------
전체백업과 부분백업


--------------------------------------------------------------------------------
전체백업
모든 데이터 파일과 컨트롤 파일을 백업하는 방식으로, 가장 보편적인 방법이다. 전체 백업은 데이터베이스 모드에 관계없이 가능하지만, 아카이브 모드인 경우와 노아카이브 모드인 경우 전체 백업을 수행했을 때의 차이가 있다.
데이터베이스 전체에 대한 백업은 다음과 같은 방법으로 가능하다.

• 컨트롤 파일 뿐만 아니라 모든 데이터 파일을 복사하는 운영체제가 제공하는 유틸리티
• RMAN BACKUP DATABASE 명령어
• 데이터베이스 내의 각 데이터 파일에 대해 수행되는 RMAN COPY DATAFILE 명령어와
컨트롤 파일에 대해 실행되는 COPY CURRENT CONTROLFILE 명령어


--------------------------------------------------------------------------------
부분백업
전체 데이터베이스를 백업하는 대신 테이블스페이스나 컨트롤 파일과 같이 일부분만을 백업하는 방법이다. 부분 백업은 아카이브 모드에서만 가능하므로, 현재 DB가 아카이브 모드인지 확인해야 한다. 부분 백업에는 테이블스페이스 백업, 데이터 파일 백업, 컨트롤 파일 백업, 아카이브 리두 로그 파일 백업이 있다.
데이터 파일의 백업 상태는 v$backup 뷰로 확인이 가능하다.

SQL> select log_mode from v$database; ☜ 현제 DB의 아카이브 모드 확인
SQL> alter database archivelog; ☜ DB의 모드를 아카이브모드로 전환


--------------------------------------------------------------------------------
테이블스페이스 백업/ 데이터 파일 백업
1) 온라인 테이블스페이스 백업하기
테이블스페이스 백업은 테이블스페이스를 구성하는 데이터 파일을 백업하는 것으로, DB가 아카이브모드라면, 온라인 또는 오프라인 상태에서도 가능하다.


SQL> select tablespace_name, file_name from dba_data_files;

TABLESPACE_NAME FILE_NAME
--------------- ------------------------------------------------------------
USERS /export/home/oracle/app/oracle/oradata/orcl/users01.dbf
SYSAUX /export/home/oracle/app/oracle/oradata/orcl/sysaux01.dbf
UNDOTBS1 /export/home/oracle/app/oracle/oradata/orcl/undotbs01.dbf
SYSTEM /export/home/oracle/app/oracle/oradata/orcl/system01.dbf

SQL> alter tablespace users begin backup; ☜ users 테이블스페이스에 대해 백업 시작을 알림

Tablespace altered.

SQL> !
$ cp /export/home/oracle/app/oracle/oradata/orcl/users01.dbf bkup/.
$ exit

SQL> alter tablespace users end backup; ☜ users 테이블스페이스에 대해 백업 종료를 알림

Tablespace altered.

SQL> select * from v$backup;

FILE# STATUS CHANGE# TIME
---------- ------------------ ---------- ------------
1 NOT ACTIVE 0
2 NOT ACTIVE 0
3 NOT ACTIVE 0
4 NOT ACTIVE 2858563 04-JAN-06

SQL>

2) 오프라인 테이블스페이스 백업하기
사용중인 테이블스페이스를 오프라인시켜 백업할 수 있다. 그러나 SYSTEM 테이블스페이스와 현재 사용중인 롤백 세그먼트는 오프라인 시킬 수 없다는 것을 의미한다.

SQL> select tablespace_name, file_name from dba_data_files;

TABLESPACE_NAME FILE_NAME
--------------- ------------------------------------------------------------
USERS /export/home/oracle/app/oracle/oradata/orcl/users01.dbf
SYSAUX /export/home/oracle/app/oracle/oradata/orcl/sysaux01.dbf
UNDOTBS1 /export/home/oracle/app/oracle/oradata/orcl/undotbs01.dbf
SYSTEM /export/home/oracle/app/oracle/oradata/orcl/system01.dbf

SQL> alter tablespace users offline normal;

Tablespace altered.

SQL> !
$ cp /export/home/oracle/app/oracle/oradata/orcl/users01.dbf bkup/.
$ exit

SQL> alter tablespace users online;

Tablespace altered.

SQL>


--------------------------------------------------------------------------------
컨트롤 파일 백업
오라클 DB를 설치하면 CREATE DATABASE 문에 의해 기본적으로 생성되는 파일들이 있는데, 리두 로그 파일, SYSTEM 데이터 파일, UNDO 데이터 파일, TEMP 데이터 파일등의 경로와 파일명을 설정한다. 정상적으로 실행되면 컨트롤 파일이 생성된다
자동으로 생성된는 컨트롤 파일에는 CREATE DATABASE 문에 의해 정의된 파일의 모든 정보가 기록된다. DB가 MOUNT 단계가 되면 컨트롤 파일의 정보를 읽어 DB의 모든 상태를 점검한다. 이때 컨트롤 파일을 읽을 수 없으면 DB를 사용할 수 없다. 따라서 컨트롤 파일을 잘 관리해야 한다. DB를 설치하면 기본적으로 3개의 컨트롤 파일이 생성되는데 첫 번째 파일이 원본 컨트롤 파일고, 나머지 두 개의 파일은 원본에 대한 미러링(mirroring) 파일로 원본 컨트롤 파일에 문제가 발생하면 미러링 파일로 복구할 수 있다.
현재 DB에서 사용하고 있는 컨트롤 파일의 위치와 이름은 v$controlfile 뷰를 참조하여 확인할 수 있다.

SQL> select * from v$controlfile;

STATUS NAME IS_
------- ------------------------------------------------------------ ---
/export/home/oracle/app/oracle/oradata/orcl/control01.ctl NO
/export/home/oracle/app/oracle/oradata/orcl/control02.ctl NO
/export/home/oracle/app/oracle/oradata/orcl/control03.ctl NO

SQL>

컨트롤 파일을 백업하는 세가지 방법
방법1) 컨트롤 파일 백업
SQL> shutdown
Database closed.
Database dismounted.
ORACLE instance shut down.
SQL> !
$ cp /export/home/oracle/app/oracle/oradata/orcl/*.ctl bkup/.
$
$ ls dbs/*.ora
dbs/init.ora dbs/initdw.ora dbs/spfileorcl.ora
initDB명.ore 파일에 복사된 컨트롤 파일을 추가 한다.
...
CONTROL_FILES=(control01.ctl,..,control04.ctl)
...
$ exit

SQL> startup
ORACLE instance started.

Total System Global Area 289406976 bytes
Fixed Size 778796 bytes
Variable Size 99360212 bytes
Database Buffers 188743680 bytes
Redo Buffers 524288 bytes
Database mounted.
Database opened.
SQL>

방법2) spfile을 사용한 컨트롤 파일 백업
SQL> ALTER SYSTEM SET control_files=
'/export/home/oracle/app/oracle/oradata/orcl/control01.ctl',
'/export/home/oracle/app/oracle/oradata/orcl/control02.ctl',
'/export/home/oracle/app/oracle/oradata/orcl/control03.ctl', SCOPE=SPFILE;
SQL> SHUTDOWN
SQL> !
# cp control01.ctl control04.ctl
# exit
SQL> STARTUP

방법3) ALTER DATABASE 명령을 사용한 방법


ALTER DATABASE BACKUP CONTROLFILE TO TRACE;

alter database 명령을 실행하여 컨트롤 파일을 백업하면 생성된 복사본은 바이너리 파일로 생성되는 대신 텍스트 형식으로 백업 파일을 저장한다. 만일 원본 컨트롤 파일과 복사본 컨트롤 파일 모두를 사용할 수 없다면, 이 파일을 사용하여 모든 컨트롤 파일을 재생성할 수 있다.
백업된 파일은 initDB명.ora 파일의 user_dump_dest 매개변수가 지정하는 경로에 *.trc 확장자로 생성된다.
이렇게 백업된 *.trc 콘트럴 파일로부터 컨트롤 파일을 다시 복구하는 방법은 이곳에 있음
다음과 같은 경우 alter database 명령문을 실행하여 컨트롤 파일에 대한 trc 파일을 생성하는 것이 좋다.

• ALTER DATABASE 명령어에 의해 db의 구조가 변경될 때
• CREATE TABLESACE 명령어에 의해 테이블스페이스가 추가 되거나 변경될 때
• DROP TABLESPACE 명령어를 사용하여 테이블스페이스가 삭제될 때

SQL> alter database backup controlfile to trace;

Database altered.

SQL> show parameter user_dump_dest;

NAME TYPE VALUE
----------------- ----------- ------------------------------------------------
user_dump_dest string /export/home/oracle/app/oracle/admin/orcl/udump
SQL>

아카이브 모드 설정하기

아카이브 모드 설정하기
먼저 현재 DB가 아카이브 모드인지 노아카이브 모드인지를 알아 보려면 V$database 뷰의 log_mode 컬럼을 학인하여 알 수 있다.


SQL> select log_mode from v$database;

LOG_MODE
------------
NOARCHIVELOG

SQL>

이제 DB를 노아카이브모드에서 아카이브 모드로 전환하는 방법을 살펴보자. 두 모드 사이의 전환은 ALTER DATABASE 명령을 사용한다.

$ sqlplus system/manager as sysdba

SQL> shutdown normal
데이터베이스가 닫혔습니다.
데이터베이스가 마운트 해제되었습니다.
ORACLE 인스턴스가 종료되었습니다.

SQL> startup mount;
ORACLE 인스턴스가 시작되었습니다.

Total System Global Area 289406976 bytes
Fixed Size 778796 bytes
Variable Size 103554516 bytes
Database Buffers 184549376 bytes
Redo Buffers 524288 bytes
Database mounted.

SQL> alter database archivelog;

Database altered.

SQL> alter database open;

Database altered.

SQL> select log_mode from v$database;

LOG_MODE
------------
ARCHIVELOG

SQL>
SQL> conn system/manager as sysdba
Connected.
SQL> archive log list;


아카이브 모드로 수행하기
아카이브 모드를 설정한 후 아카이브를 수행하는 방법은 두 가지가 있다.
1) 오라클 초기화 파일 init.ora의 변수를 이용하여 자동으로 수행하는 방법이고,
2) ALTER SYSTEM 명령으로 수동으로 실행하는 방법이 있다.

--------------------------------------------------------------------------------
자동으로 수행하기
자동으로 아카이브를 수행하기 위해 init.ora 초기화 파일에서 설정해야 하는 매개변수는 다음과 같다.


LOG_ARCHIVE_START=TRUE
LOG_ARCHIVE_DEST=[아카이브 파일의 경로와 파일이름]
LOG_ARCHIVE_DEST_n=[다른 아카이브 파일의 경로와 파일이름]
LOG_ARCHIVE_FORMAT=[포맷형식].[확장자]


각 매개변수의 특징은 다음과 같다.
LOG_ARCHIVE_START ARCH 백그라운드 프로세스에 의해 DB를 아카이브 모드로 전환하고, 로그 스위치가 발생하면 자동으로 아카이브 수행
LOG_ARCHIVE_DEST 리두 로그 파일에 대한 아카이브 파일이 생성될 기본 저장 경로
LOG_ARCHIVE_DEST_n 아카이브 경로를 여러 곳 저장할 때 사용, 최대 10개까지 경로 지정 가능
LOG_ARCHIVE_FORMAT 지정된 경로에 생성될 아카이브 파일의 파일 포맷
%s 자동으로 생성될 아카이브 파일의 일련번호 결정(예:1,2,3,..)
%S 자동으로 생성될 아카이브 파일의 일련번호를 0으로 채워 졀정 (예:000001,000002,000003,..)
%t DB가 하나의 인스턴스인지 여러 개의 인스턴스로 구성되었는지 구분하여 표시 (예:1,2,3,..)
%T DB가 하나의 인스턴스인지 여러 개의 인스턴스로 구성되었는지 0값으로 채워 구분하여 표시 (예:0001,0002,0003,..)

수동으로 수행하기
아카이브를 수동으로 실행하려면 ALTER SYSTEM ARCHIVE LOG ALL; 문을 사용한다.
이 ALTER SYSTEM 문을 실행하면 이전 백업이후 수정된 내용을 아카이브 파일에 기록한다. 자동 수행에 비해 DB 관리자가 항상 아카이브 파일에 기록할 시기를 결정하고 수행해야 함으로, 적절한 시기에 온라인 로그 파일의 내용을 아카이브 파일로 저장하지 못하면 시스템에 문제가 발생할 수 있다.

아카이브에 대한 정보 조회
archive log list; 아카이브에 대한 간단한 정보
v$database 아카이브 모드에 대한 정보
v$instance 아카이브 모드에 대한 정보
V$archived_log 실제로 아카이브 디렉토리로부터 아카이브 파일들의 존재를 확인

2009년 3월 20일 금요일

ftptransfer

cd /oracle/app/oracle/product/816
. ./.profile

TODAY=`date +'%Y_%m%d'`

BINARY_DIR=/backup/HDDWEB/bin
EXPORT_DIR=/backup/HDDWEB/exp

TARGET_DIR=/backup/HJSMS/exp
TARGET_IP=IP주소
USERNAME=oracle
PASSWORD=oracle

####### FULL EXPORT : HDDWEB ########

cd $EXPORT_DIR

#exp system/system full=y compress=y file=`date +'%Y_%m%d'`_HDDWEB01.dmp,`date +'%Y_%m%d'`_HDDWEB02.dmp,`date +'%Y_%m%d'`_HDDWEB03.dmp filesize=800m log=`date +'%Y_%m%d'`_HDDWEB.log

exp system/system full=y compress=y file=`date +'%Y_%m%d'`_HDDWEB01.dmp,`date +'%Y_%m%d'`_HDDWEB02.dmp,`date +'%Y_%m%d'`_HDDWEB03.dmp filesize=800m > ${EXPORT_DIR}/${TODAY}_HDDWEB.log
=
find $EXPORT_DIR -mtime +1 -exec rm -f {} \;

compress $EXPORT_DIR/*.dmp

####### TRANSFER EXPORT FILE VIA FTP => HJSMS ##############

function ftptransfer
{
ftp -v -n $TARGET_IP <user $USERNAME $PASSWORD
cd $TARGET_DIR
lcd $EXPORT_DIR
prompt
bin
mput $TODAY*.Z
mput $TODAY*.log
quit
ENDline
}

ftptransfer

############################################################

ls $EXPORT_DIR/$TODAY_* > $BINARY_DIR/db_export.lst

mailx -s 'FULL EXPORT : HDDWEB, HDDCC, HJTWMS, HJTEDI' aaa@bbb.co.kr < $BINARY_DIR/db_export.lst

2009년 3월 16일 월요일

TRIGGER rtsrv_cus_sgn_before

CREATE OR REPLACE TRIGGER rtsrv_cus_sgn_before
BEFORE INSERT OR DELETE
ON rtsrv_cus_sgn
FOR EACH ROW
BEGIN
IF INSERTING
THEN
INSERT INTO rtsrv_cus_sgn_trg
(rcs_wbl_num, rcs_dlv_eno, rcs_cfm_cnd,
rcs_sgn_ymd, rcs_crt_seq, rcs_crt_dtm
)
VALUES (:NEW.rcs_wbl_num, :NEW.rcs_dlv_eno, :NEW.rcs_cfm_cnd,
:NEW.rcs_sgn_ymd, rcs_crt_seq.NEXTVAL, SYSDATE
);
END IF;

IF DELETING
THEN
UPDATE rtsrv_cus_sgn_trg
SET rcs_del_dtm = SYSDATE,
rcs_del_seq = rcs_del_seq.NEXTVAL
WHERE rcs_wbl_num = :OLD.rcs_wbl_num;
END IF;
END;

TRIGGER hddht_mtr_blk_before

CREATE OR REPLACE TRIGGER hddht_mtr_blk_before
BEFORE INSERT OR DELETE
ON hddht_mtr_blk
FOR EACH ROW
BEGIN
IF INSERTING
THEN
IF :NEW.hmb_div = 'B2'
THEN
INSERT INTO hddht_mtr_blk_trg
(seq, hmb_div, hmb_dat, hmb_date,
hmb_rgt_mdh
)
VALUES (:NEW.seq, :NEW.hmb_div, :NEW.hmb_dat, :NEW.hmb_date,
:NEW.hmb_rgt_mdh
);
END IF;
END IF;

IF DELETING
THEN
IF :NEW.hmb_div = 'B2'
THEN
UPDATE hddht_mtr_blk_trg
SET hmb_del_dtm = SYSDATE
WHERE seq = :OLD.seq;

IF SQL%NOTFOUND
THEN
INSERT INTO hddht_mtr_blk_trg
(seq, hmb_div, hmb_dat,
hmb_date, hmb_rgt_mdh, hmb_del_dtm
)
VALUES (:OLD.seq, :OLD.hmb_div, :OLD.hmb_dat,
:OLD.hmb_date, :OLD.hmb_rgt_mdh, SYSDATE
);
END IF;
END IF;
END IF;
END;

SYSDBA and SYSOPER Privileges in Oracle

제목: SYSDBA and SYSOPER Privileges in Oracle
문서 ID: 50507.1 유형: REFERENCE
마지막 갱신 날짜: 02-MAR-2009 상태: PUBLISHED


Checked for relevance on 02-March-2009

0) Introduction
~~~~~~~~~~~~~~~
This article describes the different ways you can connect to Oracle as an administrative
user. It describes the options available to connect as SYSDBA and SYSOPER.

A checklist to troubleshoot SYSDBA/SYSOPER connections is documented separately :

Note 69642.1 - UNIX: Checklist for Resolving Connect AS SYSDBA Issues

Oracle 8.1 was the last release to support the 'CONNECT INTERNAL' syntax :
therefore you must use SYSDBA or SYSOPER privileges in current releases.

1) Administrative Users
~~~~~~~~~~~~~~~~~~~~~~~
There are two main administrative privileges in Oracle: SYSOPER and SYSDBA

(In version 11g this has been augmented by the SYSASM privilege, this basically
works in the same manner technically but will not be addressed here
see Note 429098.1 "11g ASM New Feature" for more information)

SYSDBA and SYSOPER are special privileges as they allow access to a database instance
even when it is not running and so control of these privileges is totally outside of
the database itself.

SYSOPER privilege allows operations such as:
Instance startup, mount & database open ;
Instance shutdown, dismount & database close ;
Alter database BACKUP, ARCHIVE LOG, and RECOVER.
This privilege allows the user to perform basic operational tasks without the ability to look at user data.

SYSDBA privilege includes all SYSOPER privileges plus full system privileges
(with the ADMIN option), plus 'CREATE DATABASE' etc..
This is effectively the same set of privileges available when previously
connected INTERNAL.


2) Password or Operating System Authentication
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Password Authentication
~~~~~~~~~~~~~~~~~~~~~~~
Unless a connection to the instance is considered 'secure' then you MUST use a
password to connect with SYSDBA or SYSOPER privilege.

When the passwordfile is initially created with the uility orapwd it holds the password for
user SYS, other users can be added to the password file with the 'GRANT SYSDBA to &USER;' command.

Such a user can then connect to the instance for administrative purposes using
the syntax:

CONNECT username/password AS SYSDBA

or

CONNECT username/password AS SYSOPER

This is described in more detail in section (5) below.


Operating System Authentication
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If the connection to the instance is local or 'secure' then it is possible to
use the operating system to determine if a user is allowed SYSDBA or SYSOPER
access. In this case no password is required.
The syntax to connect using operating system authentication is:

CONNECT / AS SYSDBA
or
CONNECT / AS SYSOPER


Oracle determines if you can connect thus:

On Unix/Linux:

On UNIX the Oracle executable has two group names compiled into it,
one for SYSOPER and one for SYSDBA.
These are known as the OSOPER and OSDBA groups.
Typically these can be set when the Oracle software is installed.

When you issue the command 'CONNECT / AS SYSOPER' Oracle checks if
your Unix logon is a member of the 'OSOPER' group and if so allows you
to connect.
Similarly to connect as SYSDBA your Unix logon should be a member of
the Unix 'OSDBA' group.
The OSDBA groups is the same group as has been historically used to
allow CONNECT INTERNAL.


On MS Windows NT/2000/2003/XP:

On MS Windows the OSOPER and OSDBA groups are hard coded groups thus:

Group Name Oracle uses this as...
~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~
ORA_OPER OSOPER group for all instances
ORA_DBA OSDBA group for all instances

or

ORA_sid_OPER OSOPER group for a specific Oracle SID
ORA_sid_DBA OSDBA group for a specific Oracle SID

When you issue a 'CONNECT / AS SYSDBA' , Oracle checks if your MS Windows logon is a
member of the 'ORA_sid_DBA' or 'ORA_DBA' group.


3) OSDBA & OSOPER Groups on Unix/Linux
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The 'OSDBA' and 'OSOPER' groups are chosen at installation time and usually both default
to the group 'dba'. These groups are compiled into the 'oracle' executable and so are the
same for all databases running from a given ORACLE_HOME directory.
The actual groups being used for OSDBA and OSOPER can be checked thus:

cd $ORACLE_HOME/rdbms/lib
cat config.[cs]

The line '#define SS_DBA_GRP "group"' should name the chosen OSDBA group.
The line '#define SS_OPER_GRP "group"' should name the chosen OSOPER group.

If you wish to change the OSDBA or OSOPER groups this file needs to be modified
either directly or using the installer.

Eg: For an OSDBA group of 'mygroup'

If your platform has config.c (this is the case for HP-UX, Compaq Tru64
Unixware and Linux):

Change: #define SS_DBA_GRP "dba"
to: #define SS_DBA_GRP "mygroup"

If your platform has config.s:
Due to the way different compilers under different architectures generate
assembler code, it's not possible to give a universal rule.

Here are some examples:
Sun SPARC Solaris:
------------------
Change both ocurrences of
.ascii "dba\0"
to
.ascii "mygroup\0"

IBM AIX/Intel Solaris:
----------------------
Change both ocurrences of
.string "dba"
to
.string "mygroup"

To effect any changes to the groups and to be sure you are using the groups
defined in this file relink the Oracle executable.
Be sure to shutdown all databases before relinking:

Eg:
mv config.o config.o.orig
make -f ins_rdbms.mk ioracle

(Note config.o will be re-created by make because of dependencies automatically)

For a group to be accepted by Oracle as the OSDBA or OSOPER group it must:

- Be compiled into the Oracle executable
- The group name must exist in /etc/group (or in 'ypcat group' if NIS is being
used)
- It CANNOT be the group called 'daemon'


Note: The commands above are examples and may vary between platforms.
Note: Some Oracle documentation refers to the ability to define OSDBA and OSOPER
roles using group names of the form 'ORA_sid_OSDBA'.
This functionality has not been implemented on Unix (See Bug 224071)


Disabling Operating System Authentication
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Given the above information about the technical implementation details of OS authenication it is
possible to disable OS authentication by putting non-existant OS group names in the config.c
(or config.s) file, then (re)move the config.o and relink oracle, however this is not supported
for the following reasons:

- Many tools like RMAN rely on the OS authentication to work, in any documentation and references
this behaviour is expected to work.
- If you disable OS authentication like this the administrative connections AS SYSDBA/SYSOPER can only
make use of the passwordfile, if there's something wrong with it no one can login, if you consider
in a broader sense that availability is also part of security then this means it negatively impacts
the security of your system.
- Moreover it only provides a false sense of security since a DBA with access to the oracle software
owner can rebuild the password file or relink oracle to restore it.


Important notes about 'CONNECT / AS SYSDBA'
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
On Unix systems a user may be a member of more than one group.
To connect as an administrative user without supplying a password:

- One of the groups of which the user is a member should be either the OSDBA or
OSOPER groups as defined in config.c (config.s on some platforms) and as
linked into the 'oracle' executable.
- The group must be a valid group as defined in /etc/group (or as defined in NIS
by 'ypcat group')
- The users PRIMARY group (Ie: the one shown by the 'id' command) cannot be the
special group 'daemon'.

It is quite common for the 'root' user to be required to have SYSDBA or SYSOPER
privilege. Unfortunately it is also common for the root users' primary group to be the
group 'daemon' which may prevent it from being allowed to connect without a password.
There are two ways to tackle this problem:

a) Make the root users PRIMARY group the OSDBA group
OR
b) Where available use the 'newgrp' command to change the users primary group to
the DBA group.
Eg: $ newgrp dbagroup
$ sqlplus /nolog
SQL> connect / as sysdba

This can also be used in shellscripts thus:

:
newgrp dbagroup <# Commands requiring connect internal privilege
# Eg: dbstart
!

OR
c) For systems where 'newgrp' is not available or does not work from scripts you
can use 'su' instead.
Eg:
:
su - oracle <# Commands requiring administrative connect privilege
!

Note: The user you 'su' to should be able to 'connect / as sysdba' without a
password, for example by having their primary group as the OSDBA group.

Some Oracle releases have problems with identifying the OSDBA group when it is
not the users primary group.
If you encounter problems with connecting and the OSDBA group is set correctly
try making the users primary group the OSDBA group, or use 'newgrp' as in (b)
above.


4) OSDBA & OSOPER Groups on MS Windows
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The 'OSDBA' and 'OSOPER' groups on NT are simply groups with the name "ORA_DBA",
"ORA_OPER", "ORA_sid_DBA" or "ORA_sid_OPER", where 'sid' is the instance name.

Eg: To make a user an administrative user simply:

a) Ensure there is a line in the SQLNET.ORA file which reads:
SQLNET.AUTHENTICATION_SERVICES = (NTS)
b) Create a LOCAL user
c) Create a local NT group ORA_DBA or ORA_sid_DBA where 'sid' is in upper case
d) Add the user to the ORA_DBA or ORA_sid_DBA group
e) That user should now be able to "connect / as sysdba"

If these requirements are not met, you get an ORA-01031 error.

Domain prefixed usernames
~~~~~~~~~~~~~~~~~~~~~~~~~
It is possible to set up usernames which include the domain as a prefix to the
username.
Eg: "OPS$\".
To do this you need to use the registry entry OSAUTH_PREFIX_DOMAIN and creating
users with USERNAMEs of the form "OPS$\".
This is described in detail in Note 60634.1


5) Password Authentication
~~~~~~~~~~~~~~~~~~~~~~~~~~
Remote connections require the database to be configured to allow remote DBA
operations. The remote user will have to supply a password in order to connect
as either SYSDBA or SYSOPER. The only real exception to this is on MS Windows
where remote connections may be secure.

Ie: To perform a remote connect as SYSDBA or SYSOPER you must use the syntax
'CONNECT username/password AS SYSDBA'

To allow remote administrative connections you must:

- Set up a password file for the database on the server
- Set up any relevant init.ora parameters


5.1) Setting up a Password File
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The SYSDBA/SYSOPER password protection is controlled by an Oracle 'Password'
file. The basic concept is that a special file is created to hold the 'SYSDBA' and
'SYSOPER' passwords. Users with SYSDBA or SYSOPER privilege granted in the
password file can be seen in the view V$PWFILE_USERS.

To create a password file log in as the Oracle software owner and issue the
command:

orapwd file= password= entries=

using the required password.

On Unix/Linux the passwordfile convention is : $ORACLE_HOME/dbs/orapw$ORACLE_SID
On MS Windows the passwordfile convention is : %ORACLE_HOME%\database\PWD%ORACLE_SID%.ORA

Except in a Database Vault installation, the location on Windows 32-bit is
%ORACLE_HOME%\dbs\orapw%ORACLE_SID%, see Note 429818.1

The file name is important and should be specified as above.
You should create this file when the database is shut down.

To change a password you can use the syntax: ALTER USER &DBAUSER identified by &newpassword,
the changes will be synchronized in the passwordfile, in case this does not work you can recreate
the passwordfile as follows:

- Check v$pwfile_users and note the SYSDBA and SYSOPER privileges being granted.
- Shut down the database.
- Rename the password file.
- Issue a new ORAPWD command with a new password to set the SYS password
- Grant SYSDBA and/or SYSOPER to the other users from the first step.


5.2) Setting up the Init.Ora file
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
To enable remote administrative connections set the init.ora parameters thus:

REMOTE_LOGIN_PASSWORDFILE=EXCLUSIVE

EXCLUSIVE forces the password file to be tied exclusively to a single instance.
To disable remote administrative connections set REMOTE_LOGIN_PASSWORDFILE=NONE

Note: The setting of REMOTE_OS_AUTHENT does NOT affect the ability to connect as
SYSDBA or SYSOPER from a remote machine. This parameter was deprecated in 11g and
should not be used, it is for 'normal' users that use OS authentication and therefore
it is not relevant to this discussion.

Note: Some (old) documentation may indicate SQL*Net needs configuring to connect
from remote machines.
In particular the following are NOT used:

SQL*Net V2: The REMOTE_DBA_OPS_ALLOWED / REMOTE_DBA_OPS_DENIED parameters are
irrelevant

6) Special Notes
~~~~~~~~~~~~~~~~~~~~~~~~~

Common Errors
~~~~~~~~~~~~~

ORA-01031: insufficient privileges
Connect Internal has been issued with no password.
For local connections the user is NOT in the DBA group as compiled
into the 'oracle' executable.
For remote connections you must always supply a password.

This error can also occur after a successful connect internal/password if there
REMOTE_LOGIN_PASSWORDFILE is either unset or set to NONE in the init.ora file.


ORA-01017: invalid username/password; logon denied
This is a fairly general error that indicates one of the following:
- REMOTE_LOGIN_PASSWORDFILE is set to NONE
- The password file does not exist
- The password supplied does not match the one in the password file
- The password file been changed since the instance was started


Deleting/Changing the Password File
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

If you delete the Oracle password file while the instance is running you will
NOT be able to connect AS SYSDBA from remote machines, even if you re-create the
file.
You must:
- Shutdown the instance (using a local connection)
- Create the new password file
- You can now connect remotely and restart the instance

Pro*C Fails To Precompile With The Error Code 139 When The Precompiler Version Is Lower Than The Oracle Client Version

제목: Pro*C Fails To Precompile With The Error Code 139 When The Precompiler Version Is Lower Than The Oracle Client Version
문서 ID: 432913.1 유형: PROBLEM
마지막 갱신 날짜: 25-SEP-2007 상태: PUBLISHED

In this Document
Symptoms
Cause
Solution



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



Applies to:
Precompilers - Version: 9.2.0.1 to 9.2.0.7
This problem can occur on any platform.

Symptoms
Pro*C fails to precompile with the error 139


make -f demo_proc.mk build EXE=daemon OBJS=daemon.o PROCFLAGS="sqlcheck=semantics parse=full userid=storeq/storeq123"



/usr/ccs/bin/make -f /mnt/raid1/apps/oracle/product/9.2.0.1/precomp/demo/proc/demo_proc.mk PROCFLAGS="sqlcheck=semantics parse=full userid=storeq/storeq123" PCCSRC=daemon I_SYM=include= pc1
proc sqlcheck=semantics parse=full userid=storeq/storeq123 iname=daemon include=. include=/mnt/raid1/apps/oracle/product/9.2.0.1/precomp/public include=/mnt/raid1/apps/oracle/product/9.2.0.1/rdbms/public include=/mnt/raid1/apps/oracle/product/9.2.0.1/rdbms/demo include=/mnt/raid1/apps/oracle/product/9.2.0.1/plsql/public include=/mnt/raid1/apps/oracle/product/9.2.0.1/network/public

Pro*C/C++: Release 9.2.0.1.0 - Production on Thu Apr 26 14:48:48 2007

Copyright (c) 1982, 2002, Oracle Corporation. All rights reserved.

System default option values taken from: /mnt/raid1/apps/oracle/product/9.2.0.1/precomp/admin/pcscfg.cfg

*** Error code 139
make: Fatal error: Command failed for target `pc1'
Current working directory /export/home/oracle/plsql/storeq
*** Error code 1
make: Fatal error: Command failed for target `daemon.o'




Cause
This problem is faced whenever the precompiler version is not upgraded to the latest patchset applied.


e.g.
The precompiler version is 9.2.0.1 and the oracle client version is 9.2.0.8 .






Solution

Upgrade the proc precompiler version to 9.2.0.8.0



-relinking the precompiler
cd $ORACLE_HOME/precomp/lib
make -f ins_precomp.mk proc


OR

-reapplying the 9.2.0.8 patchset after the Pro*C installation

2009년 3월 11일 수요일

8.1.6 DB Upgrade Script

* Target hostname: hjtour
* Target DB Name: hjmall, hjmat, hjrtc
* Oracle Login User: oracle4

* Oracle Home
- Oracle 8.1.6 Home(Source): /oracle4/app/oracle/product/816
- Oracle 8.1.6 Home(Target): /oracle4/app/oracle/product/817

* 엔진 위치
- Oracle 8.1.6 엔진 백업: /backup/DBUpgrade/oracle816_bak
- Oracle 8.1.7 엔진 임시 위치: /backup/DBUpgrade/oracle8174_temp

* Manual Upgrade Scripts
/backup/DBUpgrade/scripts/HJMALL/1.sql ~ 45.sql
/backup/DBUpgrade/scripts/HJMAT/1.sql ~ 45.sql
/backup/DBUpgrade/scripts/HJRTC/1.sql ~ 45.sql

* 준비 사항
- begin backup & end backup 스크립트 작성
Begin Backup Script: /backup/DBUpgrade/scripts/begin_backup.sh
End Backup Script: /backup/DBUpgrade/scripts/end_backup.sh
- 원복 시나리오 준비
1) 백업되는 컨트롤 파일, 데이터 파일, 리두 로그 파일, 아카이브 로그 디렉토리 결정
2) 원복 용도의 init.ora 파일 미리 작성
3) 원복 시 수행할 db file rename 스크립트 준비








< 사전 작업 #1 – 기존 엔진 백업 및 8.1.7 엔진 구축 작업 >
순서 대상 설명 작업 스크립트
1 21
(telnet) 서버 로그인 [ Login 21 svr oracle4 user ] (select any instance)
2 21
(telnet) 8.1.6 엔진 백업 cd /backup/DBUpgrade
mkdir oracle816_bak
cd oracle816_bak
cp –r /oracle4 ./
2 21
(telnet) 8.1.7 엔진용 임시 저장 디렉토리 생성. 해당 디렉토리로 이동 cd /backup
mkdir DBUpgrade
cd DBUpgrade
mkdir oracle8174_temp
cd oracle8174_temp
3 21
(ftp) oracle 8.1.7 엔진을 ftp를 통해 다운로드 ftp 172.16.201.61
[ id/pw: oracle/oracledba ]
bin
cd /ims/backup/UPGRADE
get oracle8174_aix.tar.Z
quit
4 21
(telnet) 엔진 압축 해제 zcat oracle8174_aix.tar.Z | tar -xvf -
5 21
(telnet) 8.1.7 홈의 내용을 oracle 파일 시스템에 복사 cd /backup/DBUpgrade/oracle8174_temp/oracle/app/oracle/product
cp –r 817 /oracle4/app/oracle/product
6 21
(telnet) 현 OS 유저 환경 설정 파일을 8.1.7 홈에 복사
(.profile, .alias) cp $ORACLE_HOME/.profile /oracle4/app/oracle/product/817
cp $ORACLE_HOME/.alias /oracle4/app/oracle/product/817
7 21
(telnet) 현 DB 관련 설정 파일들을 8.1.7 홈에 복사
(orapwd, init) cp $ORACLE_HOME/dbs/orapwd* /oracle4/app/oracle/product/817/dbs
cp $ORACLE_HOME/dbs/init*.ora /oracle4/app/oracle/product/817/dbs
8 21
(telnet) 현 DB 관련 네트웍 관련 파일을 8.1.7 홈에 복사
(listener, tnsnames) cd /oracle/app/oracle/product/817/network/admin
cp $ORACLE_HOME/network/admin/tnsnames.ora ./
cp $ORACLE_HOME/network/admin/listener.ora ./


< 사전 작업 #2 – 파라미터 파일 변경 작업 >
순서 대상 설명 작업 스크립트
1 21
(telnet) [ Login 21 svr oracle4 user ] ( select HJMALL instance )
2 21
(telnet) 8.1.7 홈의 OS 설정 파일에 대해 수정(.profile, .alias) cd /oracle4/app/oracle/product/817
vi .profile (이전 8.1.6 Oracle Home을 가리키는 경로를 8.1.7 로 변경)
#export ORACLE_HOME=$ORACLE_BASE/product/816
export ORACLE_HOME=$ORACLE_BASE/product/817
vi .alias (8.1.6 Oracle Home을 가리키는 경로를 8.1.7 로 변경)
3 21
(telnet) 8.1.7 홈의 init.ora 에 대해 복제본 생성 cd dbs
cp initHJMALL.ora initHJMALL.ora_org
cp initHJMAT.ora initHJMAT.ora_org
cp initHJRTC.ora initHJRTC.ora_org
4 Migration을 위한 init.ora 수정. [ Edit init.ora file for migration ]
vi /oracle4/app/oracle/product/817/dbs/initHJMALL.ora
vi /oracle4/app/oracle/product/817/dbs/initHJMAT.ora
vi /oracle4/app/oracle/product/817/dbs/initHJRTC.ora
## Commented out Prameters
# job_queue_processes = 0
# aq_tm_processes = 0
## Added Paramters
_system_trig_enable = false
optimizer_mode = rule
5 listener.ora 의 ORACLE_HOME 항목 변경 vi /oracle4/app/oracle/product/817/network/admin/listener.ora
(ORACLE_HOME = /oracle4/app/oracle/product/816)
 (ORACLE_HOME = /oracle4/app/oracle/product/817)







< 사전 작업 #3 –DB 파일 백업 작업 >
순서 대상 설명 작업 스크립트
1 21
(telnet) 서버 로그인 [ Login 21 svr oracle4 user ] ( select HJMALL instance )
3 21
(telnet) 관련 DB(HJMALL) Hot 백업 모드로 전환 cd /backup/DBUpgrade/scripts
export ORACLE_SID=HJMALL
begin_backup.sh
4 21
(telnet) 데이터 파일 백업 cd /mall02
mkdir /mall02/HJMALL_BAK
cd HJMALL_BAK
cp –r /mall01/HJMALL/indx /mall02/HJMALL_BAK
cp –r /mall01/HJMALL/sysdata /mall02/HJMALL_BAK
cp –r /mall02/HJMALL/data /mall02/HJMALL_BAK
5 21
(dbms) 컨트롤 파일 백업 sqlplus '/ as sysdba'
alter database backup controlfile to '/backup/HJMALL_BAK/control01.ctl'
exit
cp control01.ctl control02.ctl
cp control01.ctl control03.ctl
6 21
(telnet 관련 DB(HJMALL) Normal 모드로 전환 cd /backup/DBUpgrade/scripts
end_backup.sh













< 업그레이드 작업 – 8.1.6  8.1.7 Manual Upgrade : HJMALL >

순서 DB Ver 작업 스크립트
0 8.1.6 Manual 실행 업그레이드 스크립트 다운로드 cd /backup/DBUpgrade/scripts
mkdir HJMALL
cd HJMALL
ftp 172.16.201.61
[ id/pw: oracle/oracledba ]
cd /ims/backup/UPGRADE/
get upgrade_scripts.tar
quit
tar xvf upgrade_scripts.tar
1 8.1.6 Backup 수행
(DB 및 Engine 백업)
(1) Oracle 데이터 파일 백업
(2) Oracle 엔진 백업 (위 사전 작업으로 추가 작업 필요 없음)
2 8.1.6 필수 OS Patch 검사 -
3 8.1.6 필수 Kernel 파라미터 검사 -
4 8.1.6 ORACLE_HOME, SID 확인 04.sh
5 8.1.6 DBMS Version과 Option 검토 svrmgrl

05.sql
exit
6 8.1.6 svrmgrl 수행 svrmgrl
connect internal
7 8.1.6 DB Character Set 검토 07.sql
8 8.1.6 딕셔너리 손상 체크 08.sql
9 8.1.6 Valid 하지 않는 object 확인 09.sq
10 8.1.6 - -
11 8.1.6 Snapshot refresh 완료 확인 11.sql
(존재 시 작업이 완료 때 까지 기다리거나 중지 시켜야 함)
exit
12 8.1.6 리스너 중지 lsnrctl stop
13 8.1.6 복구 파일 존재 여부 확인 svrmgrl
connect internal
13.sql
(복구 해야 하는 파일이 없어야 함. 존재한다면 복구 해야 함)
14 8.1.6 백업 모드가 아닌 파일 확인 14.sql
(백업 모드인 파일이 없어야 함. 백업 모드를 종료 해야 함)
15 8.1.6 미해결 분산 트랜잭션 확인 15.sql
(존재할 경우 해소 해야 함)
16 8.1.6 ( 해당 사항 없음 ) -
17 8.1.6 모든 Batch와 Cron 비활성화 -
18 8.1.6 SYSTEM 롤백 세그먼트 준비 18.sql
19 8.1.6 SYSTEM 테이블 스페이스 공간확인 19.sql
(50 MB 이상 필요)
20
21 8.1.6 sys, system 유저의 기본 TBS 확인 20.sql
( 모두 SYSTEM 이어야 함. 그렇지 않으면 21.sql 수행 )
22 8.1.6 AUD$ 테이블 기본 TBS 확인 22.sql
(SYSTEM 이어야 함)
23 8.1.6 v$controlfile 의 내용 기록 23.sql
24 8.1.6 v$pwfile_users 의 내용 기록 24.sql
25-1 8.1.6 DB Shutdown shutdown immediate
exit
25-2 8.1.6 archive log, redo log 파일을 백업 위치에 복사
26 init.ora 수정 (위 사전 작업으로 추가 작업 필요 없음)
27 Archive 파일 시스템 확인 df –k /arch
28 NLS_LANG 확인 echo $NLS_LANG
29 listener.ora, tnsnames.ora 복사 (위 사전 작업으로 추가 작업 필요 없음)
30 (해당 사항 없음) -
31 (해당 사항 없음) -
32 (해당 사항 없음) -
33 8.1.7 새로운 DB 홈의 .profile 수행 /oracle/app/oracle/product/817/. .profile
34 8.1.7 환경 변수 확인 34.sh 수행
35 8.1.7 업그레이드 스크립트 수행 svrmgrl
connect internal
startup restrict
35.sql
36 8.1.7 DB Shutdown SHUTDOWN IMMEIDATE
37 8.1.7 (replication 이용하지 않음) -
38 8.1.7 (replication 이용하지 않음)
39 8.1.7 utlrp 수행으로 패키지 컴파일 cd /backup/DBUpgrade/scripts/HJMALL
svrmgrl
connect internal
startup restrict
39.sql
exit
40 8.1.7 원래의 init.ora로 복원 cd $ORACLE_HOME/dbs
cp initHJMALL.ora_org initHJMALL.ora
41 8.1.7 데이터베이스 재 시작 svrmgrl
Connect internal
Shutdown
Startup
exit
42 8.1.7 listener.ora에 ORACLE_HOME 변경 (위 사전작업으로 추가 작업 필요 없음)
43 8.1.7 리스너 시작 lsnrctl start
44 8.1.7 Cron 과 Batch 잡 수행 -

Complete Upgrade Checklist for Manual Upgrades from 8.x to 8.x

제목: Complete Upgrade Checklist for Manual Upgrades from 8.x to 8.x
문서 ID: 133920.1 유형: BULLETIN
마지막 갱신 날짜: 03-APR-2008 상태: PUBLISHED


Checked for relevance on 02-OCT-2006

PURPOSE
-------

This document is created for use as a guideline and checklist when
manually upgrading oracle.


SCOPE & APPLICATION
-------------------

Database adminstrators


UPGRADE CHECKLIST
-----------------

1. ----------------------------------------------------------------------------

Perform a complete online backup!!!! (or a full cold backup if you prefer)

-- root account crontab info: /usr/tivoli/tsm/backup/onbackup.sh
-- =======================================================================
-- TOTAL STATUS: SUCCESS
-- START DATE & TIME: 2009-03-12 15:10
-- END DATE & TIME: 2009-03-13 14:09
-- TOTAL SIZE: 1045 GB
-- TSM SERVER: HJSMS_TSM
-- TSM CLIENT: HDDDB
-- =======================================================================

2. ----------------------------------------------------------------------------

Verify all necessary OS patches are installed.
Example for Solaris:
$ showrev -p
--Example for AIX:
--# instfix -iak

3. ----------------------------------------------------------------------------

Verify the kernel parameters according to the installation guide of the
new version
Example for Solaris:
$ cat /etc/system

4. ----------------------------------------------------------------------------

Ensure ORACLE_SID is set to instance you want to upgrade.
Echo $ORACLE_SID
Echo $ORACLE_HOME

5. ----------------------------------------------------------------------------

What version is running? What option is installed?
Select * from v$version;
Select * from v$option;

6. ----------------------------------------------------------------------------

I the procedural option installed(pl/sql)?
Start svrmgrl

7. ----------------------------------------------------------------------------

Verify characterset of the database:
$ Sqlplus SYS/
Select name, substrb(value$,1,40) value from props$;

8. ----------------------------------------------------------------------------

Check for corruption in the dictionary, use:

Set verify off
Set space 0
Set heading off
Set feedback off
Set pages 1000
Spool analyze.sql
Select 'Analyze '||object_type||' '||object_name
||' validate structure;'
from dba_objects
where owner='SYS'
and object_type in ('INDEX','TABLE','CLUSTER');
spool off
This creates a script called analyze.sql.
Run the script.

This script (analyze.sql) should not return any errors.

9. ----------------------------------------------------------------------------

List all objects that are not VALID. After migration all objects will be
invalid, this list returns a list of fatal objects.

Select substr(owner,1,12) owner, substr(object_name,1,30) object,
Substr(object_type,1,30) type,status from dba_objects where status <>'VALID';

To create a script to compile all invalid objects run the following, this
creates a script Obj.sql.

set verify off
set space 0
Set heading off
Set feedback off
Set pages 1000

spool obj.sql
select 'set termout on' from dual;
select 'set echo on' from dual;

select 'alter trigger '||owner||'.'||object_name||' compile;'
from dba_objects
where status <> 'VALID'
and object_type='TRIGGER';

select 'alter package '||owner||'.'||object_name||' compile;'
from dba_objects
where status <> 'VALID'
and object_type='PACKAGE';

select 'alter package '||owner||'.'||object_name||' compile body;'
from dba_objects
where status <> 'VALID'
and object_type='PACKAGE BODY';

select 'alter procedure '||owner||'.'||object_name||' compile;'
from dba_objects
where status <> 'VALID'
and object_type='PROCEDURE';

select 'alter function '||owner||'.'||object_name||' compile;'
from dba_objects
where status <> 'VALID'
and object_type='FUNCTION';

select 'alter view '||owner||'.'||object_name||' compile;'
from dba_objects
where status <> 'VALID'
and object_type='VIEW';
/
spool off
Run the script and than rerun the query to get invalid objects.

spool invalid_pre.lst
Select substr(owner,1,12) owner,
Substr(object_name,1,30) object,
Substr(object_type,1,30) type, status from
dba_objects where status <>'VALID';
spool off

This creates a file with a list of invalid objects.

10. ---------------------------------------------------------------------------

List the grants,
If the upgrade fails and at the dictionary was already rebuild, grants are lost.
If you want to go back it is advisable to have a list of grants. Use the
following script:
#!/bin/sh
#
# struct.sh
#--:
#--: generates DDL of database
#--:
ORAENV_ASK=NO; export ORAENV_ASK
ORACLE_SID=$3; export ORACLE_SID
. oraenv
ORAENV_ASK=YES; export ORAENV_ASK
Exp userid=$1/$2 file=/tmp/struct compress=no full=y rows=n
Imp userid=$1/$2 file=/tmp/struct full=y show=y 2> /tmp/contents.lst
Rm /tmp/struct.dmp
Awk ' BEGIN { prev=";" }
/ \"CREATE / { N=1; }
/ \"ALTER / { N=1; }
/ \"ANALYZE / { N=1; }
/ \"GRANT / { N=1; }
/ \"REVOKE / { N=1; }
/ \"COMMENT / { N=1; }
/ \"AUDIT / { N=1; }
N==1 { printf "\n/\n\n"; N++ }
/\"$/ { prev=""
if (N==0) next;
s=index( $0, "\"" );
if ( s!=0 ) {
printf "%s",substr( $0,s+1,length( substr($0,s+1))-1 )
prev=substr($0,length($0)-1,1 );
}
if (length($0)<78) printf( "\n" );
}' < /tmp/contents.lst > /tmp/struct1
rm /tmp/contents.lst
sed /^$/d < /tmp/struct1 > /tmp/struct2
rm /tmp/struct1
fold -s -w75 /tmp/struct2 > $3.sql
rm /tmp/struct2

The script takes 3 arguments username, password and SID. The script SID.sql
Is generated. If only grants are needed, change the line:
' fold -s -w75 /tmp/struct2 > $3.sql '
by
' grep ^GRANT /tmp/struct2 | fold -s -w75 > $3.sql '

11. ---------------------------------------------------------------------------

Ensure that all Snapshot refreshes are succesfully completed.
And replication is stopped.
$ Sqlplus SYS/
Select distinct(trunc(last_refresh)) from dba_snapshot_refresh_times;

12. ---------------------------------------------------------------------------

Stop the listener for the database
$ lsnrctl
Lsnrctl> stop

13. ---------------------------------------------------------------------------

Ensure no files need media recovery:
$ sqlplus SYS/
Select * from v$recover_file;

This should return no rows

14. ---------------------------------------------------------------------------

Ensure no files are in backup mode:
Select * from v$backup where status!='NOT ACTIVE';

This should return no rows.

15. ---------------------------------------------------------------------------

Resolve any outstanding unresolved distributed transaction:

Select * from dba_2pc_pending;

If this returns rows you should do the following:

Select local_tran_id from dba_2pc_pending;
Execute dbms_transaction.purge_lost_db_entry('');
Commit;

16. ---------------------------------------------------------------------------

If you are upgrading from an 8.0 release check no users or roles are called
either MIGRATE or OUTLN.

Select * from dba_users where username in ('MIGRATE','OUTLN');
Select * from dba_roles where role in ('MIGRATE','OUTLN');

If so these users/roles will need to be dropped prior to migration.

17. ---------------------------------------------------------------------------

Disable all batch and cron jobs.

18. ---------------------------------------------------------------------------

Prepare the system rollback segment:
Alter rollback segment system storage (maxextents 121 next 1M);

19. ---------------------------------------------------------------------------

Ensure plenty of free space in the SYSTEM tablespace. A minimum of 50 Mb
free space.

Select max(bytes) from dba_free_space where tablespace_name='SYSTEM';

20. ---------------------------------------------------------------------------

Ensure the users sys and system have 'system' as their default tablespace.

Select username, default_tablespace from dba_users where username
in ('SYS','SYSTEM');

21. ---------------------------------------------------------------------------

To modify use:
Alter user sys default tablespace SYSTEM;
Alter user system default tablespace SYSTEM;

22. ---------------------------------------------------------------------------

Ensure aud$ table is in System tablespace when auditing is enabled.
Select tablespace_name from dba_tables where table_name='AUD$';

If the aud$ table is in a non-SYSTEM Tablespace then auditing needs
to be disabled before migration. This is because auditing will try to
acquire a non-system rollback segment. However these are all taken
offline during migration.

Auditing during migration can only be achieved with the aud$ in
the System tablespace, as use will be made of the System rollback
segment.

23. ---------------------------------------------------------------------------

Note down where all control files are located.
Select * from v$controlfile;

24. ---------------------------------------------------------------------------

Note down all sysdba users.
Select * from v$pwfile_users;

If a passwordfile is used copy it to the new location. On unix the default
is $ORACLE_HOME/dbs/orapw. On windows NT this is
%ORACLE_HOME%\database\orapw

25. ---------------------------------------------------------------------------

Shutdown the database
$ svrmgrl
SVRMGR> Shutdown immediate

26. ---------------------------------------------------------------------------

Change the init.ora file:
- Make a backup of the init.ora file.
- Ensure there is a value for DB_BLOCK_SIZE
- Comment out the JOB_QUEUE_PROCESSES parameter, put in a new and set this
explicitly to zero, during the upgrade
- Comment out the AQ_TM_PROCESSES parameter, put in a new and set this
explicitly to zero, during the upgrade
- If archiving is enabled set LOG_ARCHIVE_START=TRUE
- Ensure that the USER_DUMP_DEST, BACKGROUND_DUMP_DEST and the CORE_DUMP_DEST
are set to an explicit directory
- Set the parameter _SYSTEM_TRIG_ENABLED explicitly to FALSE during the upgrade.
Note: Only applies for upgrades/migrations to 8i/9i. See Note 149948.1 for
further information.
- Set the parameter OPTIMIZER_MODE to RULE during the upgrade. This is a
workaround for Bug 1362374.
- Comment out obsoleted parameters(list in appendix A).
- Comment out SNAPSHOT_REFRESH_? parameters
- Ensure the COMPATIBLE parameter points to the current
Version. This to ensure a more easy downgrade when something goes wrong.
We can alter this to point to the new release when everything is tested.

27. ---------------------------------------------------------------------------

Check for adequate freespace on archive log destination file systems.

28. ---------------------------------------------------------------------------

Ensure the NLS_LANG variable is set correctly:
$ echo $NLS_LANG

29. ---------------------------------------------------------------------------

If needed copy the listener.ora and the tnsnames.ora to the new location
(when no TNS_ADMIN env. Parameter is used)
cp $ORACLE_HOME/network/admin /network/admin

30. ---------------------------------------------------------------------------

If your Operating system is Windows NT, delete your services
With the ORADIM of your old oracle version.

C:\ORADIM80 ?DELETE ?SID ORCL

And create the ORACLE 8I service:

C:\ORADIM ?NEW ?SID ORCL ?INTPWD -MAXUSERS n
-STARTMODE AUTO ?PFILE ORACLE_HOME\DATABASE\init.ora

31. ---------------------------------------------------------------------------

If needed copy the init.ora file to the new oracle_home or
Create a link to the init.ora.
cp $OLD_ORACLE_HOME/dbs/init.ora $NEW_ORACLE_HOME/dbs/init.ora
OR
Ln ?s /init/ora/file/path/init.ora $ORACLE_HOME/dbs/init.ora
Also check 'ifile' parameters in the init.ora, to be set to the correct file.
if an IFILE is used, verify the above mentioned parameter for the init.ora
and copy this to the correct location. Change the IFILE entry in the init.ora
file when this file changes from location.

32. ---------------------------------------------------------------------------

Update the oratab entry, to set the new ORACLE_HOME and disable automatic
startup:
::N

33. ---------------------------------------------------------------------------

Update the enviroment variables like ORACLE_HOME and PATH
$ . oraenv

34. ---------------------------------------------------------------------------

Make sure the following enviroment variables point to the new
Release directories:
- ORACLE_HOME
- PATH
- ORA_NLS33
- ORACLE_BASE
- LD_LIBRARY_PATH
- ORACLE_PATH

For HP-UX systems verify the SHLIB_PATH parameter points to the new release
directories.

$ env | grep ORACLE_HOME
$ env | grep PATH
$ env | grep ORA_NLS33
$ env | grep ORACLE_BASE
$ env | grep LD_LIBRARY_PATH
$ env | grep ORACLE_PATH

HP-UX:
$ env | grep SHLIB_PATH

35. ---------------------------------------------------------------------------

Run the upgrade script:
$ cd /$ORACLE_HOME/rdbms/admin
Svrmgrl
SVRMGR> Connect internal
SVRMGR> Startup restrict
SVRMGR> Spool catoutu.log
Run the appropriate script for your version.

From To Only Script to Run
==== === ==================
8.0.3 8.0.4 or higher @u0800030.sql
8.0.4 8.0.5 or higher @u0800040.sql
8.0.5 8.0.6 or higher @u0800050.sql
8.0.6 8.1.5 or higher @u0800060.sql
8.1.3 8.1.5 or higher @u0801030.sql
8.1.4 8.1.5 or higher @u0801040.sql
8.1.5 8.1.6 or higher @u0801050.sql
8.1.6 8.1.7 @u0801060.sql

SVRMGR> spool off

Each of these scripts are a direct upgrade path from the version you are
on to 8.1.x. You do not need to run catalog.sql and catproc.sql as these
two scripts are called from within the upgrade script.

Possible problem:
You have just installed the binaries for Oracle 8.1.6. You alreadyhave
Oracle 8.1.5 installed and a database created with 8.1.5. You want to
manually upgrade the 8.1.5 database to 8.1.6. You did not install the
Migration Utility, because you are going to upgrade manually. When you
actually run the the following script:

u0801050.sql

You receive an error 'cannot find i0801050.sql'.

Solution 1:

The i0801050.sql is not installed unless you install the Migration
Utility, eventhough it is required when upgrading the database
Manually. So, you must go back and install the Migration Utility.

Solution 2:

Using your favorite text editor, create the i0801050.sql script in
$ORACLE_HOME/rdbms/admin and add the following instruction:

alter table argument$ add pls_type varchar2(30);
-- 30 = M_IDEN

Now rerun your upgrade procedure and it should complete without errors.

The file i0801050.sql is called by the script u0801050.sql. This file is
only installed with the Migration Utility.

36. ---------------------------------------------------------------------------

Shutdown the database and startup in restricted mode:
SVRMGR> Shutdown (DO NOT USE SHUTDOWN ABORT!!!!!!!!!)
SVRMGR> Startup restrict

37. ---------------------------------------------------------------------------

Run catrep script if replication is used:

$ cd $ORACLE_HOME/rdbms/admin
$ svrmgrl
SVRMGR> connect internal
SVRMGR> Startup restrict
SVRMGR> spool catoutrp.log
SVRMGR> @catrep

38. ---------------------------------------------------------------------------

Run post-catrep advanced replication upgrade script, if needed:
Run the appropriate script for your version.

From Only Script to Run
==== ==================
8.0.3 @r0800030.sql
8.0.4 @r0800040.sql
8.0.5 @r0800050.sql
8.0.6 @r0800050.sql (Same as 8.0.5)

This script do not exist for upgrades from an earlier 8.1.x version.
As it is not necessary to run this script when upgrading from an
earlier 8.1.x version.

39. ---------------------------------------------------------------------------

Run script to recompile invalid pl/sql modules:
SVRMGR> @utlrp

40. ---------------------------------------------------------------------------

Edit init.ora file:
- put back the old value for the job_queue_processes parameter
- put back the old value for the aq_tm_processes parameter
- remove the parameter _system_trig_enabled from the init.ora file. This
parameter was explicitly set to false during the upgrade.
- modify the log_archive_dest parameter specify only the path, but make sure it
ends with a '/'. (remove the format)
e.g. log_archive_dest=/path/arch into log_archive_dest=/path/
- Modify the marameter log_archive_format and add the format previously
removed from the log_archive_dest.
E.g log_archive_format=arch%t_SID_%s.log

41. ---------------------------------------------------------------------------

Shutdown the database and startup the database normal.
$ svrmgrl
SVRMGR> Connect internal
SVRMGR> Shutdown
SVRMGR> Startup

42. ---------------------------------------------------------------------------

Modify the listener.ora file:
For the upgraded intstance(s) modify the ORACLE_HOME parameter
to point to the new ORACLE_HOME.
--Before: (ORACLE_HOME = /oracle2/app/oracle/product/816)
--After: (ORACLE_HOME = /oracle2/app/oracle/product/817)
43. ---------------------------------------------------------------------------

Start the listener
$ lsnrctl
LSNRCTL> start

44. ---------------------------------------------------------------------------

Enable cron and batch jobs

45. ---------------------------------------------------------------------------

Change oratab entry to use automatic startup
SID:ORACLE_HOME:Y
--Before: HDDDB:/oracle2/app/oracle/product/816:N
--After: HDDDB:/oracle2/app/oracle/product/817:N


46. ---------------------------------------------------------------------------

When everything is well tested, update the compatible parameter in the
init.ora file and restart to the new release number.
Compatible=8.1.x where x is the release number

--/oracle2/app/oracle/admin/HDDDB/pfile/initHDDDB.ora
--Before: compatible = "8.1.0"
--After: compatible = "8.1.7"

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

Appendix A: Obsolete parameter


8.1.5 Obsolete parameters:

spin_count
shared_pool_reserved_min_alloc
large_pool_min_alloc
use_ism
lock_sga_areas
lgwr_io_slaves
arch_io_slaves
backup_disk_io_slaves
ogms_home
parallel_transaction_resource_timeout
db_block_checkpoint_batch
db_block_lru_statistics
db_block_lru_extended_statistics
compatible_no_recovery
log_archive_buffers
log_archive_buffer_size
log_block_checksum
log_small_entry_max_size
log_simultaneous_copies
db_file_simultaneous_writes
log_files
gc_lck_procs
gc_latches
freeze_DB_for_fast_instance_recovery
temporary_table_locks
delayed_logging_block_cleanouts
cleanup_rollback_entries
discrete_transactions_enabled
sequence_cache_entries
sequence_cache_hash_buckets
row_cache_cursors
distributed_lock_timeout
max_transaction_branches
distributed_recovery_connection_hold_time
close_cached_open_cursors
sort_direct_writes
sort_write_buffers
sort_write_buffer_size
sort_spacemap_size
sort_read_fac
b_tree_bitmap_plans
complex_view_merging
push_join_predicate
fast_full_scan_enabled
job_queue_keep_connections
snapshot_refresh_processes
snapshot_refresh_interval
snapshot_refresh_keep_connections
parallel_default_max_instances
cache_size_threshold
parallel_server_idle_time
allow_partial_sn_results
ops_admin_group
parallel_min_message_pool


8.1.6 Obsolete parameters:

spin_count
shared_pool_reserved_min_alloc
large_pool_min_alloc
use_ism
lock_sga_areas
lgwr_io_slaves
arch_io_slaves
backup_disk_io_slaves
ogms_home
parallel_transaction_resource_timeout
db_block_checkpoint_batch
db_block_lru_statistics
db_block_lru_extended_statistics
compatible_no_recovery
log_archive_buffers
log_archive_buffer_size
log_block_checksum
log_small_entry_max_size
log_simultaneous_copies
db_file_simultaneous_writes
log_files
gc_lck_procs
gc_latches
freeze_DB_for_fast_instance_recovery
temporary_table_locks
delayed_logging_block_cleanouts
cleanup_rollback_entries
discrete_transactions_enabled
sequence_cache_entries
sequence_cache_hash_buckets
row_cache_cursors
distributed_lock_timeout
max_transaction_branches
distributed_recovery_connection_hold_time
close_cached_open_cursors
sort_direct_writes
sort_write_buffers
sort_write_buffer_size
sort_spacemap_size
sort_read_fac
b_tree_bitmap_plans
complex_view_merging
push_join_predicate
fast_full_scan_enabled
job_queue_keep_connections
snapshot_refresh_processes
snapshot_refresh_interval
snapshot_refresh_keep_connections
optimizer_search_limit (not obsolete in 8.1.5)
parallel_default_max_instances
cache_size_threshold
parallel_server_idle_time
allow_partial_sn_results
ops_admin_group
parallel_min_message_pool


8.1.7 Obsolete parameters:
spin_count
shared_pool_reserved_min_alloc
large_pool_min_alloc
use_ism
lock_sga_areas
lgwr_io_slaves
arch_io_slaves
backup_disk_io_slaves
ogms_home
parallel_transaction_resource_timeout
db_block_checkpoint_batch
db_block_lru_statistics
db_block_lru_extended_statistics
compatible_no_recovery
log_archive_buffers
log_archive_buffer_size
log_block_checksum
log_small_entry_max_size
log_simultaneous_copies
db_file_simultaneous_writes
log_files
gc_lck_procs
gc_latches
freeze_DB_for_fast_instance_recovery
temporary_table_locks
delayed_logging_block_cleanouts
cleanup_rollback_entries
discrete_transactions_enabled
sequence_cache_entries
sequence_cache_hash_buckets
row_cache_cursors
distributed_lock_timeout
max_transaction_branches
distributed_recovery_connection_hold_time
close_cached_open_cursors
sort_direct_writes
sort_write_buffers
sort_write_buffer_size
sort_spacemap_size
sort_read_fac
b_tree_bitmap_plans
complex_view_merging
push_join_predicate
fast_full_scan_enabled
job_queue_keep_connections
snapshot_refresh_processes
snapshot_refresh_interval
snapshot_refresh_keep_connections
optimizer_search_limit
parallel_default_max_instances
cache_size_threshold
parallel_server_idle_time
allow_partial_sn_results
ops_admin_group
parallel_min_message_pool