oracle blog(?)에 oracle 11g로 upgrade해야할 이유 6개가 나왔네요. 

오라클 support 기간 종료, security 문제에 대한 fix, 그리고 new feature의 이점들.. 
뭐 훌륭한 feature 들이 많은건 일단 인정.. 
그래도 가장 큰 이유는 support 기간 종료가 아닐까.. 싶네요. 

#1: Oracle support period will end soon or has ended.

#2: The application provider is pushing you to uprgade.

#3: CPU or PSUs - security fixes.

#4: Potential cost savings part 1.

#5: Potential cost savings part 2.

#6: Faster access to LOB data - move to Secure Files.


출처 : Why upgrade?


아래 blog 내용 처럼 v$lock을 조회할때 그리 시간이 많이 걸리는 경험은 없었던것 같지만..
v$lock을 조회하면 내부 fixed table join시 'MERGE JOIN CARTESIAN'이 사용되며 여기에 비용이 많이 든다는 군요.
혹시 v$lock query 결과가 늦으시면 ordered hint를 써보심이...


SQL statement for V$LOCK!!! 
select s.inst_id,l.laddr,l.kaddr,s.ksusenum,r.ksqrsidt,r.ksqrsid1, r.ksqrsid2,l.lmode,l.request,l.ctime,decode(l.lmode,0,0,l.block) from v$_lock l, x$ksuse s, x$ksqrs r where l.saddr=s.addr and concat(USERENV('Instance'),l.raddr)=concat(r.inst_id,r.addr) and s.inst_id = USERENV('Instance'); 




oracle index rebuild를 판단하는 기준이나 rebuild가 필요한지 자체에 대한 많은 말들이 있긴한데.. 

다음의 글은 index_stats view의 del_lf_rows를 이용한 index rebuild 방안에 대한 구조적인 한계에 대한 설명입니다.
뭐 이러한 방안을 대량 delete 작업 후 바로 적용하면 될 거 같은데,
아래와 같은 내용을 알아둬야 .. 수치가 좀 이상하게 나올 경우 당황하지 않겠네요~ 

But, as the Oracle myth busters like Richard Foote have been saying for years,  that's not how Oracle's B-tree indexes work. When you delete an index entry, Oracle marks it as deleted but leaves it in place. When you commit your transaction Oracle does nothing to the index entry – but other processes now know that the entry can be wiped from the block allowing the space to be re-used.      (원문 : Index Rebuilds « Oracle Scratchpad )




alert log file은 오라클 데이터베이스 운영을 위해서는 꼭 확인해야 하는 가장 기본적인 log file이다. 
이 기본적인 alert log file은 이름처럼 꼭 alert을 안줘도 될만한 정보까지도 alerting(?)질을 하곤 하는데, 
online redo log size가 너무 작거나 변경량이 많은 경우 그 내용이 너무 많아 관리자들은 확인에 소홀해 지기도 한다.
하지만 꼭 봐야한다!!  

아래 기술한 내용은 alert log file을 '날짜|로그' format으로 변경해주는 awk 명령이다. 
가끔 장애가 발생하면 연관 서버, 업무들을 시간 순으로 나열할 일이 생기는데 요런 작업을 좀 편하게 해보려고 만들어 봤다.  
추가로 alert log file을 external table을 이용해 DB에 loading 하는 것까지 추가한다. 

1. awk 명령을 이용해 "시간|로그내용"으로 변경하기

+ alert log file

Fri Jul 29 13:40:01 2011
Thread 1 advanced to log sequence 292352
  Current log# 2 seq# 292352 mem# 0: /FS/redo02a.log
  Current log# 2 seq# 292352 mem# 1: /FS/redo02b.log
Thread 1 advanced to log sequence 292353
  Current log# 3 seq# 292353 mem# 0: /FS/redo03a.log
  Current log# 3 seq# 292353 mem# 1: /FS/redo03b.log
Fri Jul 29 13:42:19 2011
Thread 1 advanced to log sequence 292354
  Current log# 4 seq# 292354 mem# 0: /FSredo04a.log
  Current log# 4 seq# 292354 mem# 1: /FSredo04b.log
Fri Jul 29 13:50:01 2011
Thread 1 advanced to log sequence 292355
  Current log# 5 seq# 292355 mem# 0: /FSredo05a.log
  Current log# 5 seq# 292355 mem# 1: /FSredo05b.log
Thread 1 advanced to log sequence 292356
  Current log# 1 seq# 292356 mem# 0: /FSredo01a.log
  Current log# 1 seq# 292356 mem# 1: /FSredo01b.log
Fri Jul 29 13:53:57 2011
Thread 1 advanced to log sequence 292357
  Current log# 2 seq# 292357 mem# 0: /FS/redo02a.log
  Current log# 2 seq# 292357 mem# 1: /FS/redo02b.log

+ awk 명령을 이용해 날짜와 로그 내용을 병합한다. 
 
$ tail -100 /bdump/alert_SID.log | awk '{if (($5=="2011") && $6 =="") {vdate = $0} else {print vdate,"|", $0} }' | grep 2011 > /fs/app/oracle/product/rdbms/log/alert_test.log

$ cat  /fs/app/oracle/product/rdbms/log/alert_test.log
 
Fri Jul 29 13:42:19 2011 | Thread 1 advanced to log sequence 292354
Fri Jul 29 13:42:19 2011 |   Current log# 4 seq# 292354 mem# 0: /FS/redo04a.log
Fri Jul 29 13:42:19 2011 |   Current log# 4 seq# 292354 mem# 1: /FS/redo04b.log
Fri Jul 29 13:50:01 2011 | Thread 1 advanced to log sequence 292355
Fri Jul 29 13:50:01 2011 |   Current log# 5 seq# 292355 mem# 0: /FS/redo05a.log
Fri Jul 29 13:50:01 2011 |   Current log# 5 seq# 292355 mem# 1: /FS/redo05b.log
Fri Jul 29 13:50:01 2011 | Thread 1 advanced to log sequence 292356
Fri Jul 29 13:50:01 2011 |   Current log# 1 seq# 292356 mem# 0: /FS/redo01a.log
Fri Jul 29 13:50:01 2011 |   Current log# 1 seq# 292356 mem# 1: /FS/redo01b.log
Fri Jul 29 13:53:57 2011 | Thread 1 advanced to log sequence 292357
Fri Jul 29 13:53:57 2011 |   Current log# 2 seq# 292357 mem# 0: /FS/redo02a.log
Fri Jul 29 13:53:57 2011 |   Current log# 2 seq# 292357 mem# 1: /FS/redo02b.log
Fri Jul 29 14:00:02 2011 | Thread 1 advanced to log sequence 292358
Fri Jul 29 14:00:02 2011 |   Current log# 3 seq# 292358 mem# 0: /FS/redo03a.log
Fri Jul 29 14:00:02 2011 |   Current log# 3 seq# 292358 mem# 1: /FS/redo03b.log
Fri Jul 29 14:00:02 2011 | Thread 1 advanced to log sequence 292359
Fri Jul 29 14:00:02 2011 |   Current log# 4 seq# 292359 mem# 0: /FS/redo04a.log
Fri Jul 29 14:00:02 2011 |   Current log# 4 seq# 292359 mem# 1: /FS/redo04b.log

2. 변경된 alert log file을 DB로 loading 하기

+ DB내 directory 정보 확인 
SQL> select * from dba_directories;

OWNER                          DIRECTORY_NAME                 DIRECTORY_PATH
------------------------------ ------------------------------ -----------------------------------
SYS                            DATA_PUMP_DIR                  /fs/app/oracle/product/rdbms/log/

+ external table 만들기 
 
SQL> drop table t_alert_log;
SQL> create table t_alert_log (ldate varchar2(25), text_line varchar2(150)) 
 organization external
 (
   type oracle_loader 
   default directory DATA_PUMP_DIR
   ACCESS PARAMETERS 
   ( 
    records delimited by newline 
    fields terminated by '|' 
   ) 
 location ('alert_test.log')); 

+ 입맛대로 query 하기 
 
SQL> select rownum,a.* from t_alert_log a;
 
    ROWNUM LDATE                     TEXT_LINE
---------- ------------------------- ------------------------------------------------------------------------
       386 Fri Jul 29 13:30:17 2011     Current log# 1 seq# 292351 mem# 0: /FS/redo01a.log
       387 Fri Jul 29 13:30:17 2011     Current log# 1 seq# 292351 mem# 1: /FS/redo01b.log
       388 Fri Jul 29 13:40:01 2011   Thread 1 advanced to log sequence 292352
       389 Fri Jul 29 13:40:01 2011     Current log# 2 seq# 292352 mem# 0: /FS/redo02a.log
       390 Fri Jul 29 13:40:01 2011     Current log# 2 seq# 292352 mem# 1: /FS/redo02b.log
       391 Fri Jul 29 13:40:01 2011   Thread 1 advanced to log sequence 292353
       392 Fri Jul 29 13:40:01 2011     Current log# 3 seq# 292353 mem# 0: /FS/redo03a.log
       393 Fri Jul 29 13:40:01 2011     Current log# 3 seq# 292353 mem# 1: /FS/redo03b.log
       394 Fri Jul 29 13:42:19 2011   Thread 1 advanced to log sequence 292354
       395 Fri Jul 29 13:42:19 2011     Current log# 4 seq# 292354 mem# 0: /FS/redo04a.log
       396 Fri Jul 29 13:42:19 2011     Current log# 4 seq# 292354 mem# 1: /FS/redo04b.log

external table의 경우 text file을 loading 한 순서로 보여주므로 log file의 순서대로 보여주게 되나
이 데이터를 다른 table에 옮길경우엔 반드시 rownum을 같이 넘겨여 한다.
안그러면 순서가 뒤죽박죽~ 될 수 있음.  

tar는 지정된 여러 개의 파일들을 아카이브라고 부르는 하나의 파일로 만들거나, 하나의 아카이브 파일에 집적되어 있는 여러 개의 파일을 원래의 형태대로 추출해내는 유닉스 쉘명령어이다.  tar 아카이브 파일에는 어떻게 파일명을 적든상관없지만, tar로 묶었다는 것을 분명히 해주기 위해 ".tar"라는 파일이름 확장자가 붙는다.  tar 아카이브 파일 내에 들어있는 파일들은 압축되는 것이 아니라, 단지 하나의 파일로 모아지는 것뿐이다. 

tar라는 이름은 파일들이 주로 자기테이프에 백업되고, 이따금씩 검색되기도 하던 때로부터 유래하였다. 그러나, 요즘에는 tar 아카이브가 오히려 유닉스 시스템들간에 파일들을 전송하기 위해 좀더 자주 사용되고 있다. 

자주사용되는 조합

1. 압축하기  
tar -cvzf tarfile.tar.gz ./

-c : tar 화일을 생성한다. 
-v : 생성되는 화일 절차를 보여준다. 
-f : backup 화일명을 지정 한다. Default는 "/dev/rmt0"이다. 
-z : gzip에 현재 tar를 넘겨 압축한다. 

2. 퍼미션 유지하며 압축하기 
tar -cvzp tarfile.tar.gz ./

3. 압축풀기
> tar -xvfz tarfile.tar.gz ./

4. 퍼미션 유지하며 압축풀기 #
> tar -xvfzp tarfile.tar.gz ./

5. 내용 보기 및 테스트 #
> tar -tvfz tarfile.tar 
-t : tar화일의 목차를 보여준다. 

6. 업데이트 
> tar -uvfz tarfile.tar reverse.c
tar 화일 끝에 reverse.c가 변경 되었으면 추가 한다. 

crs resource의 상태를 crs_stat 명령으로 확인해 보면 가끔 resource의 상태가 UNKNOW인 경우가 가끔 발생한다.
CRS resource가 정상적으로 가동 되지 않은 경우도 있고 또 정상적으로 가동된 것 같은데 UNKNOW인 경우도 가끔 있다.  

oracle CRS resource가 UNKNOWN 상태로 변경되는 이유는 일반적으로 CRS resource start/stop/check 시의 action script 수행이 실패할 때 status가 변경되게 된다. 다음은 CRS resource의 state가 UNKNOWN으로 변경되는 일반적인 원인이다.
    

1.  The permission of the resource trace file is incorrect.
2.  The permission of the action script and other racg script is incorrect.
3.  The server load is very heavy and the action script times out.
4.  The look up to NIS hangs or takes very long time and causes the action script to time out.


CRS resource의 action script는 다음의 명령으로 확인할 수 있다. 
crs_stat -p <resource name such as ora.node1.vip> | grep ACTION_SCRIPT

CRS resource 이름은 다음의 명령으로 확인할 수 있다.
crs_stat | grep -i name

다음은 위에 기술한 CRS resource의 UNKNOWN state의 일반적인 원인에 대해 점검해 볼 항목이다.

1.  The permission of the resource trace file if it is incorrect. 
The resource trace file in in the HOME/log/<node name>/racg directory where HOME is the the HOME directory of action script for the resource.

2.  The permission of racg scripts in the HOME/bin directory if it they are incorrect. 
HOME is the the HOME directory of action script for the resource. Please issue "ls -l HOME/bin/racg*" to get the permission of the racg script. Please issue "ls -l HOME/bin/racg*" as user oracle or a user who normally starts up failing resources.
If any of the racg script is a soft link to another file, then check the permission of the file to which the racg script is soft linked.

3.  Check crsd.log and see if the resource action script timed out. 
If it did, then check if the server load was heavy (95% used or higher) for a minute or longer at the time of the failure. Setting up OSWatcher or IPD/OS can help troubleshooting this if the timeout occurs intermittently. Also, check if the NIC was having a problem at the time of the failure. 


참고 : Common Causes for CRS Resources in UNKNOWN State (Doc ID 860441.1) 

오라클 11G R2 이전 버전에서는 BUG으로 인해 v$SQL_BIND_CAPTURE에서 TIMESTAMP 형태의 bind 값이 NULL로 보입니다. 그러나 ANYDATA.AccessTimestamp(value_anydata) 를 이용해 볼수 있는 workaround 가 있군요.

참고: V$SQL_BIND_CAPTURE Does Not Show The Value For Binds Of Type TIMESTAMP (Doc ID 444551.1)

SQL> declare 
bindts timestamp; 
begin 
bindts := systimestamp(); 
execute immediate 'select /* BIND_CAPTURE_TEST */ 1 from dual where :b1 is 
not null' using bindts; 
execute immediate 'select /* BIND_CAPTURE_TEST */ 1 from dual where :b1 is 
not null' using bindts; 
execute immediate 'select /* BIND_CAPTURE_TEST */ 1 from dual where :b1 is 
not null' using bindts; 
end; 


PL/SQL procedure successfully completed. 

SQL> select sql_id from v$sql where sql_fulltext like '%BIND_CAPTURE_TEST%' 
and sql_fulltext not like '%xxx%' and command_type = 3; 

SQL_ID 
------------- 
1mf1ch9vsr06a 

SQL> select name, position, datatype_string, was_captured, value_string, 
anydata.accesstimestamp(value_anydata) from v$sql_bind_capture where sql_id = 
'1mf1ch9vsr06a'; 

NAME POSITION DATATYPE_STRING WAS 
------------------------------ ---------- --------------- --- 
VALUE_STRING 
------------------------------------------------------------------------------ 
-- 
ANYDATA.ACCESSTIMESTAMP(VALUE_ANYDATA) 
--------------------------------------------------------------------------- 
:B1 1 TIMESTAMP YES 
05-JUL-07 12.20.23.311417000 PM


Oracle EM gridcontrol 관련 log file들. 
EM은 어려워~ 

Log / Trace files Generated during the OMS Startup

When any of the above methods are used for the OMS startup, the log/trace files will get generated in the following directories:

1.  <OMS_HOME>/opmn/log: These log files contain the entries for the execution and usage of the OPMN and OPMN-managed processes. The files are described below:

Log file name Description
ipm.log Tracks command execution and operation progress of the Process Monitor (PM) portion of the OPMN
ons.log Tracks the execution of the ONS portion of OPMN which is initialized before PM and hence is useful for early OPMN errors.
OC4J~home~default_island~1 Tracks the startup and shutdown of the OC4J home application server component.
HTTP_Server~1 Tracks the startup and shutdown of the HTTP_Server application server component.
OC4J~OC4J_EM~default_island~1 Tracks the startup and shutdown of the OC4J_EM (OMS) application server component.
OC4J~OC4J_EMPROV~default_island~1 Tracks the startup and shutdown of the OC4J_EMPROV application server component.
OC4J~OCMRepeater~default_island~1 Tracks the startup and shutdown of the OCMRepeater application server component.
WebCache~WebCache~1 Tracks the startup and shutdown of the WebCache  application server component.
WebCache~WebCacheAdmin~1 Tracks the startup and shutdown of the WebCacheAdmin application server component.
opmn.log Contains output generated by OPMN when the ipm.log and ons.log files are not available.
service.log (on Microsoft Windows only). The service.log displays any error messages generated by OPMN services while interacting with service control manager.


2.  <OMS_HOME>/sysman/log: contains the log / trace entries generated during the OMS startup. This will include the details for the repository connection issues. The files updated at startup time are:

Log / Trace file name Description
emctl.log Tracks log messages from the emctl utility.
emoms.log Log messages from the OMS application. By default, the maximum size is set to 20MB after which the file is rotated.
emoms.trc Trace messages from the OMS application. By default, the maximum size is set to 5MB with an index of 10, for file rotation.


For details about troubleshooting the OMS Process Control, refer to:

Note 730308.1: How to Troubleshoot Process Control (start, stop, check status) the 10g Oracle Management Service(OMS) Component in 10 Enterprise Manager Grid Control

참고:
How to Process Control (start, stop, check status) the 10g Oracle Management Service(OMS)? (Doc ID 298991.1)
Master Note for 10g Grid Control OMS Performance Issues (Doc ID 1161003.1)



시스템을 운영하면 가끔 특정 프로세스가 CPU를 점유해서 다른 프로세스에 영향을 끼치곤 합니다. 
이런 경우 kill -9 <process id>로 해당 프로세스를 정리하면 문제가 해결되곤 하죠. 
물론 CPU를 99%를 소모하는 프로세스는 거의 정상적이지 않은 프로세스이므로 kill 하는 게 맞지만, 
가끔 특정 batch 작업 등 많은 시간동안 수행되어 kill 시키기 아까운 프로세스들도 존재합니다. 

아래의 아이디어는 자원을 많이 먹는 프로세스를 kill 명령으로 죽이지 않고 잠시 멈춰두는 방법입니다. 

If that oracle process uses high CPU%, and don't want to kill it yet. we may use "oradebug" to suspend it.

$ ps -e -o pcpu,user,pid,args | sort -k 1 | grep 2904
62.8 oracle 2904 oracleorcl (LOCAL=NO)

SQL> oradebug suspend
Statement processed.

$ ps -e -o pcpu,user,pid,args | sort -k 1 | grep 2904
6.0 oracle 2904 oracleorcl (LOCAL=NO)

참고: http://surachartopun.com/2011/01/oradebug-man.html

물론 kill 명령도 signum (24/26)을 주면 동일하게 suspend를 시킬 수 있습니다. 


   signum   signame   Name            Description
   ___________________________________________________________________________
      0     SIGNULL   Null            Check access to pid
      1     SIGHUP    Hangup          Terminate; can be trapped
      2     SIGINT    Interrupt       Terminate; can be trapped
      3     SIGQUIT   Quit            Terminate with core dump; can be trapped
      9     SIGKILL   Kill            Forced termination; cannot be trapped
     15     SIGTERM   Terminate       Terminate; can be trapped
     24     SIGSTOP   Stop            Pause the process; cannot be trapped
     25     SIGTSTP   Terminal stop   Pause the process; can be trapped
     26     SIGCONT   Continue        Run a stopped process

이런 기능을 운영 서버에 사용하시려면 먼저 정상적으로 수행되는지는 테스트 해봐야 겠죠? 
대부분 요런 기능은 hang 같은 테스트 환경 만들 때 주로 쓰긴 합니다..만 알아서 하시길... ^^;

P.S. 
OS kill 명령에 의한 stop과 oradebug를 이용한 suspend의 차이는 뭘까요? 
suspend 된 세션은 v$session 등에서 어떤 상태로 보여질까요? 



간단히 UTL_FILE을 이용한 scott.emp 테이블 데이터 unloading 하기
create or replace procedure utl_file_test_write (
  filename   in varchar2
  )
is
   v_file            UTL_FILE.FILE_TYPE;
   v_text            VARCHAR2 (20);
   v_filename        VARCHAR2 (200);
   v_delimitedchar   CHAR (1);
BEGIN
   v_delimitedchar := CHR (124);
   v_file := UTL_FILE.FOPEN ('DATA_PUMP_DIR', filename, 'W');
   FOR rec IN
      (SELECT   empno,ename,job,mgr,hiredate,sal,comm,deptno FROM scott.emp)
   LOOP
      UTL_FILE.PUT_LINE (v_file,rec.empno|| v_delimitedchar|| rec.ename||v_delimitedchar|| 
                         rec.job||v_delimitedchar|| rec.mgr||v_delimitedchar||rec.hiredate||
                         v_delimitedchar|| rec.sal ||v_delimitedchar|| rec.comm|| v_delimitedchar|| 
                         rec.deptno  );
   END LOOP; 
   UTL_FILE.FCLOSE (v_file);
END;
/

수행 및 결과
SQL> exec utl_file_test_write ('TEST01');
SQL> !cat /oracle_home/TEST01
7369|SMITH|CLERK|7902|1980-12-17|800||20
7499|ALLEN|SALESMAN|7698|1981-02-20|1600|300|30
7521|WARD|SALESMAN|7698|1981-02-22|1250|500|30
7566|JONES|MANAGER|7839|1981-04-02|2975||20
7654|MARTIN|SALESMAN|7698|1981-09-28|1250|1400|30
7698|BLAKE|MANAGER|7839|1981-05-01|2850||30
7782|CLARK|MANAGER|7839|1981-06-09|2450||10
7788|SCOTT|ANALYST|7566|1982-12-09|3000||20
7839|KING|PRESIDENT||1981-11-17|5000||10
7844|TURNER|SALESMAN|7698|1981-09-08|1500|0|30
7876|ADAMS|CLERK|7788|1983-01-12|1100||20
7900|JAMES|CLERK|7698|1981-12-03|950||30
7902|FORD|ANALYST|7566|1981-12-03|3000||20


블로그 구경다니다가 11g에서 쓸만한 hint 하나 확인해서 공유합니다. 
구구절절한 설명 보다 아래의 예를 보는게 가장 이해하기 쉽겠네요. 


However, Oracle11g allows us to use the IGNORE_ROW_ON_DUPKEY_INDEX hint, which will silently deal with the unique constraint violation errors by simply ignoring and not inserting any row in which the unique values already exist in the table.



SQL> insert into radiohead select rownum, 'OK COMPUTER' from dual connect by level <= 12;
insert into radiohead select rownum, 'OK COMPUTER' from dual connect by level <= 12
*
ERROR at line 1:
ORA-00001: unique constraint (BOWIE.RADIOHEAD_PK_I) violated

SQL> insert /*+ ignore_row_on_dupkey_index(radiohead,radiohead_pk_i) */ into radiohead select rownum, 
'OK COMPUTER' from dual connect by level <= 12;
2 rows created.

SQL> commit;
Commit complete.

위의 예를 보면 알겠지만 unique key 값이 없는 row에 대해서만 insert가 발생합니다. 에러는 생략되고요.. 
즉 새로 입력되는 값이 기존의 unique 값과 constraint violation이 발생한다면 무시되는 거죠.. 

이 hint는 update에는 사용할 수 없습니다. 또 parallel DML과 APPEND mode일 경우에는 무시됩니다. 
몇몇 요구사항에 맞지 않는다면 ORA-38912, ORA-38915, ORA-38913이 발생합니다. 

자세한 내용은 아래 메뉴얼에서...

interval partition을 drop할 때 ORA-14758 에러가 발생하는 군요. 
메세지로만 봐서는 마지막 partition은 drop될 수 없다라는데...
분명 마지막 range의 partition도 아니고.

아래 노트를 보면 명확히 설명되어 있네요. 
마지막 partition이라는 게 처음 table을 생성할 때 만들어진 마지막 partition이며 
이후 DB에서 자동으로 interval partition을 만들때 이 partition을 참조하기 때문에 삭제하면 안된답니다. 

그럼 처음 interval partition을 만들때 마지막 partition은 안지워지니까 
주기적인 데이터 삭제용도로 사용하시려면 마지막 partition의 range에 대해 고려를 좀 해보셔야 겠죠? 

ORA-14758: Last Partition In The Range Section Cannot Be Dropped (Doc ID 882681.1)

Symptoms

You drop a partition and receive the following error:
ORA-14758: Last partition in the range section cannot be dropped

Cause

In case of interval partitioning the partitions which are created automatically depends on the last partition created as a reference while creating a table. So the last partition can not be dropped.

Example:

create table test.orders
(order_id number(12),
order_date date
)
partition by range(order_date)
interval(numtoyminterval(1, 'month'))
(partition p1 values less than (to_date('2000-01-01', 'YYYY-MM-DD')),
partition p2 values less than (to_date('2000-04-01', 'YYYY-MM-DD')),
partition p3 values less than (to_date('2000-07-01', 'YYYY-MM-DD')));

insert into test.orders values(1, to_date('2000-02-15', 'YYYY-MM-DD')) ;
insert into test.orders values(1, to_date('2000-03-15', 'YYYY-MM-DD')) ;
insert into test.orders values(1, to_date('2000-05-15', 'YYYY-MM-DD')) ;
insert into test.orders values(1, to_date('2000-06-15', 'YYYY-MM-DD')) ;
insert into test.orders values(1, to_date('2000-08-15', 'YYYY-MM-DD')) ;
insert into test.orders values(1, to_date('2000-09-15', 'YYYY-MM-DD')) ;

commit;

SQL> select table_name,partition_name,high_value from dba_tab_partitions where table_name='ORDERS';

TABLE_NAME PARTITION_NAME HIGH_VALUE
------------------------------ ------------------------------ --------------------------------------------------------------------------------
ORDERS P1 TO_DATE(' 2000-01-01 00:00:00', 'SYYYY-MM-DD HH24:MI:SS', 'NLS_CALENDAR=GREGORIA
ORDERS P2 TO_DATE(' 2000-04-01 00:00:00', 'SYYYY-MM-DD HH24:MI:SS', 'NLS_CALENDAR=GREGORIA
ORDERS P3 TO_DATE(' 2000-07-01 00:00:00', 'SYYYY-MM-DD HH24:MI:SS', 'NLS_CALENDAR=GREGORIA
ORDERS SYS_P115 TO_DATE(' 2000-09-01 00:00:00', 'SYYYY-MM-DD HH24:MI:SS', 'NLS_CALENDAR=GREGORIA
ORDERS SYS_P116 TO_DATE(' 2000-10-01 00:00:00', 'SYYYY-MM-DD HH24:MI:SS', 'NLS_CALENDAR=GREGORIA

SQL> alter table test.orders drop partition SYS_P116;

Table altered.

SQL> alter table test.orders drop partition P2;

Table altered.

SQL> alter table test.orders drop partition P3;
alter table test.orders drop partition P3
*
ERROR at line 1:
ORA-14758: Last partition in the range section cannot be dropped

Solution

This is expected behaviour.
Do not drop the last partition on which the interval partitions are based.

오류에 대해 좀 찾아 보니 interval을 임시로 바꿔 지우는 방법이 나와 있습니다. 
하지만 오라클쪽 자료(metalink)에는 그런 내용은 없는 것 같습니다. 
요 방법 써도 괜찮을라나? 


임시 테이블은 사용자가 DML(update, insert, delete) 문을 실행한 후, 트랜젝션을 종료(commit)하면 변경된 데이터들이 테이블에 저장되지 않는 테이블이다. 어떤 응용을 개발할 때 데이터를 잠시 저장하는 변수와 같은 유형이다.

temporary table은 특정 session 또는 transaction 동안만 data를 저장한다. 

on commit delete rows : 
트랜젝션을 발생시킨 후, commit문을 실행할 때 없어지는 방법. 한 transaction 동안만 data를 저장(default임)

on commit preserve rows : 
트랜젝션을 종료하면(commit) 테이블 내에 데이터가 저장되었다가 세션을 종료하면 임시 테이블에 저장되었던 데이터들이 모두 없어지는 방법. 한 session 동안만 data를 저장

temporary table은 다음과 같은 성격을 갖는다. 

TABLE의 definition 정보는 data dictionary에 영구적으로 저장되지만, data는 일시적으로 저장된다.
CREATE로 TABLE 생성시 SEGMENT가 할당되는 것이 아니라 첫 번째 INSERT시 할당된다.
DML 작업시 해당 data에 대해 LOCK을 걸지 않는다.
data 변경시 redo log에 기록이 남지 않는다.

다음은 간단한 테스트 이다. 

1. global temporary table 생성 

SQL> create global temporary table gtt ( x int );

Table created.

2. object 생성 확인 

SQL> select dbms_metadata.get_ddl( 'TABLE', 'GTT' ) from dual;

DBMS_METADATA.GET_DDL('TABLE','GTT')
--------------------------------------------------------------------------------
  CREATE GLOBAL TEMPORARY TABLE "SCOTT"."GTT"
   (    "X" NUMBER(*,0)
   ) ON COMMIT DELETE ROWS

SQL> select object_name,object_type from user_objects where object_name = 'GTT';

OBJECT_NAME                    OBJECT_TYPE
------------------------------ ------------
GTT                            TABLE

SQL> select table_name from user_tables where table_name = 'GTT';

TABLE_NAME
------------
GTT

SQL> select table_name,temporary,duration from user_tables where table_name = 'GTT';

TABLE_NAME           TEM DURATION
-------------------- --- ---------------------------------------------
GTT                  Y   SYS$TRANSACTION

SQL> select segment_name from user_segments where segment_name = 'GTT';

no rows selected

SQL> drop table gtt;

Table dropped.

3. global temporary table 생성 

SQL> create global temporary table gtt ( x int ) on commit preserve rows;

Table created.

4. object 생성 확인 

SQL> select dbms_metadata.get_ddl( 'TABLE', 'GTT' ) from dual;

DBMS_METADATA.GET_DDL('TABLE','GTT')
--------------------------------------------------------------------------------
  CREATE GLOBAL TEMPORARY TABLE "SCOTT"."GTT"
   (    "X" NUMBER(*,0)
   ) ON COMMIT PRESERVE ROWS


SQL> select object_name,object_type from user_objects where object_name = 'GTT';

OBJECT_NAME                    OBJECT_TYPE
------------------------------ ------------- 
GTT                            TABLE

SQL> select table_name from user_tables where table_name = 'GTT';

TABLE_NAME
-------------------- 
GTT

SQL> select table_name,temporary,duration from user_tables where table_name = 'GTT';

TABLE_NAME           TEM DURATION
-------------------- --- ---------------------------------------------
GTT                  Y   SYS$SESSION

SQL> select segment_name from user_segments where segment_name = 'GTT';

no rows selected

SQL> drop table gtt;

Table dropped.



> netstat -an | grep 1521 

LISTEN       : 호스트가 임의의 원격지로부터 연결요구를 기다리는 상태
SYN-SENT     : 호스트는 연결 요구를 보내고 완전 이중통신 방식의 연결을 완료하여 답변을 기다리는 상태
SYN-RECEIVED : 호스트는 세션 연결 요구를 기다리는 상태
ESTABLISHED  : 두호스트간의 세션 연결이 성립되어 데이터 전송에 사용이 되는 상태
FIN-WAIT1    : 호스트가 원격지 호스트로부터 연결 종료 요구나 더 일찍 보내졌던 연결 종료 요구의 승인중 하나를 기다리는 상태
FIN-WAIT2    : 호스트가 원격지 호스트로부터 연결 종료 요구를 기다리는 상태
CLOSE-WAIT   : TCP 연결이 상위 레벨 응용프로그램으로 부터 연결 종료를 기다리는 상태
CLOSING      : 호스트가 원격지 호스트로부터 연결 종료 요구 승인을 기다리는 상태
LAST-ACK     : 호스트가 이미 원격지 호스트에 보내진 연결 종료 요구의 승인을 기다리는 상태
TIME-WAIT    : 호스트가 원격지 호스트의 연결 종료 요구의 승인을 수신했음을 보장하기 위해서 충분한 시간을 기다리는 상태
CLOSED       : 두 호스트간에 어떤 연결도 존재하지 않는 상태



* Veritas VCS log 확인 
cat /var/adm/syslog.log | egrep 'Nov 27 00|NOV 27 01' | egrep 'VCS|oracle' | grep -v tty
* strace / tusc / truss 사용
Linux: strace -o /tmp/truss.out -aef sqlplus "/ as sysdba"
HP: tusc -afpo /tmp/truss.out -aef sqlplus "/ as sysdba"
AIX/ Solaris: truss -aefo (output file) (executable)

* OS system log file & error messages
SOLARIS : 
System log file /var/adm/messages

HP : 
System log file /var/adm/syslog/syslog.log
Display system/error messages /usr/sbin/dmesg

Linux :
System log file /var/log/messages
Display system/error messages dmesg
  
AIX :
System log file /var/adm/ras/errlog   
Display system/error messages /bin/errpt -a  

WINDOWS :
Event viewer. click on actions >> export list

HOT backup mode에서 왜 redo log에 추가 정보가 쓰일까요? 
ALTER DATABASE BEGIN BACKUP과 ALTER TABLESPACE BEGIN BACKUP의 차이는? 

아래 두개의 POST에 모든 답이 있네요.. 

Why is excessive redo generated during an Online/Hot Backup

There is not excessive redo generated, there is additional information logged into the online redo log during a hot backup the first time a block is modified in a tablespace that is in hot backup mode.  

in hot backup mode only 2 things are different:

o the first time a block is changed in a datafile that is in hot backup mode, the ENTIRE BLOCK is written to the redo log files, not just the changed bytes.  Normally only the changed bytes (a redo vector) is written. In hot backup mode, the entire block is logged the FIRST TIME.  This is because you can get into a situation where the process copying the datafile and DBWR are working on the same block simultaneously.  Lets say they are and the OS blocking read factor is 512bytes (the OS reads 512 bytes from disk at a time).

The backup program goes to read an 8k Oracle block.  The OS gives it 4k.  Meanwhile -- DBWR has asked to rewrite this block.  the OS schedules the DBWR write to occur right now.  The entire 8k block is rewritten.  The backup program starts running again (multi-tasking OS here) and reads the last 4k of the block.  The backup program has now gotten an impossible block -- the head and tail are from two points in time.  We cannot deal with that during recovery.  Hence, we log the entire block image so that during recovery, this block is totally rewritten from redo and is consistent with itself at least.  We can recover it from there.

o the datafile headers which contain the SCN of the last completed checkpoint are NOT updated while a file is in hot backup mode.  This lets the recovery process understand what archive redo log files might be needed to fully recover this file.

Why is excessive redo generated during an Online/Hot Backup

What about ALTER DATABASE BEGIN BACKUP ?
That command put all database tablespaces in backup mode at the same time. As seen previously, it is a bad idea to put all tablespaces in backup mode, as it is better to do it one by one in order to minimize the supplemental redo logging overhead. Oracle introduces this ‘shortcut’ for one reason only: when doing backup with a mirror split (BCV, Flashcopy, etc), the copy gets all the datafiles at the same time, and the copy lasts only few seconds. In that case, it is easier to use that command to put all tablespaces in backup mode during the operation.

http://narashimreddy.wordpress.com/2009/09/11/oracle-backup-and-recovery-description-of-begin-backup-end-backup/


Oracle LOCAL INDEX를 drop하는 방법은 없습니다. ㅋ
아래 테스트를 보시면 local partition index로 만들어진 index는 drop이 되지 않는 군요.. 

LOCAL partition index는 partition table의 구조를 참조해서 만들어 지기 때문에 drop이 되지 않습니다. 
그러나 Global partition index는 자신만의 구조를 갖기 때문에 drop이 가능합니다.. 

+ LOCAL INDEX

SQL> create table p_emp (sal number(10))
 2  partition by range (sal)
 3   (partition emp_p1 values less than (2000),
 4    partition emp_p2 values less than (3000),
 5    partition emp_max values less than (maxvalue));

Table created.

SQL> create index p_emp_i on p_emp (sal) local;

Index created.

SQL> alter index p_emp_i drop partition emp_p1;
alter index p_emp_i drop partition emp_p1
           *
ERROR at line 1:
ORA-14076: submitted alter index partition/subpartition operation is not valid for local partitioned index

+ GLOBAL INDEX

 1  create table p_emp (empno number(4), sal number(10))
 2  partition by range (sal)
 3   (partition emp_p1 values less than (2000),
 4    partition emp_p2 values less than (3000),
 5*   partition emp_pmax values less than (maxvalue))
SQL> /

Table created.

 1  create index p_emp_i on p_emp (sal)
 2  global  partition by range (sal)
 3   (partition emp_p1 values less than (2000),
 4    partition emp_p2 values less than (3000),
 5*   partition emp_max values less than (maxvalue))
SQL> /

Index created.

SQL>
SQL> alter index p_emp_i drop partition emp_p2;

Index altered.

+ 참고

UTL_FILE을 이용해 file을 loading 하는 아주 간단한 example. 

declare
   fp utl_file.file_type;
   str varchar2(48);
   VAL SCOTT.TEST%ROWTYPE;   
begin
   fp := utl_file.fopen('DATA_PUMP_DIR','sample_data.txt','r');
   loop
    utl_file.get_line(fp,str);
    VAL.CUST_ID := TRIM(SUBSTR(str,1,9));
    VAL.FC_ID := TRIM(SUBSTR(str,11,20));
    insert into SCOTT.TEST values(VAL.CUST_ID,VAL.FC_ID);
   end loop;
exception
when no_data_found then
   commit;
end;
/


네이버 지식인에 DBMS_JOB으로 만들어진 JOB의 interval을 1초로 지정해도 
5초 정도의 interval을 갖는다는 질문이 있어 간단히 테스트 해 봤습니다. 

DBMS_JOB package로 job을 생성합니다 
SQL> variable jobno number;
SQL> begin
SQL> dbms_job.submit(:jobno,'insert into test values (sysdate);',
SQL> sysdate,'sysdate+1/60/24/50',FALSE);
SQL> end;
SQL> /

PL/SQL procedure successfully completed.

SQL> print jobno
     JOBNO
----------
        21

SQL> exec dbms_job.run(21);
PL/SQL procedure successfully completed.

SQL> commit;
Commit complete.

SQL> select * from user_jobs;

       JOB LOG_USER                       PRIV_USER                      SCHEMA_USER                    LAST_DATE LAST_SEC         THIS_DATE THIS_SEC         NEXT_DATE NEXT_SEC         TOTAL_TIME B
---------- ------------------------------ ------------------------------ ------------------------------ --------- ---------------- --------- ---------------- --------- ---------------- ---------- -
INTERVAL
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  FAILURES
----------
WHAT
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
NLS_ENV
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
MISC_ENV                                                           INSTANCE
---------------------------------------------------------------- ----------
        21 SYS                            SYS                            SYS                            12-OCT-10 16:50:28                                    12-OCT-10 16:50:29                  0 N
sysdate+1/60/24/50
         0
insert into test values (sysdate);
NLS_LANGUAGE='AMERICAN' NLS_TERRITORY='AMERICA' NLS_CURRENCY='$' NLS_ISO_CURRENCY='AMERICA' NLS_NUMERIC_CHARACTERS='.,' NLS_DATE_FORMAT='DD-MON-RR' NLS_DATE_LANGUAGE='AMERICAN' NLS_SORT='BINARY'
0102000202000000                                                          0

JOB 내역을 보면 정상적으로 NEXT_DATE는 LAST_DATE + 1초로 나옵니다 

SQL> alter session set nls_date_format = 'YYYY/MM/DD HH24:MI:SS';
Session altered.

SQL> select * from test;
COMMIT_DATE
-------------------
2010/10/12 16:50:04
2010/10/12 16:50:08
2010/10/12 16:50:13
2010/10/12 16:50:18
2010/10/12 16:50:23
2010/10/12 16:50:28
2010/10/12 16:50:33
2010/10/12 16:50:38
2010/10/12 16:50:43
2010/10/12 16:50:48
2010/10/12 16:50:53
2010/10/12 16:50:58
2010/10/12 16:51:03
2010/10/12 16:51:08

14 rows selected.

그러나 table에 들어간 시간을 보니 4초 차이가 발생하는 군요...

SQL> exec dbms_job.broken(21,TRUE);
PL/SQL procedure successfully completed.

SQL> exec dbms_job.remove(21);
PL/SQL procedure successfully completed.

SQL> delete from test;
25 rows deleted.

SQL> commit;
Commit complete.

이번엔 DBMS_SCHEDULER로 테스트 해봤습니다. 

SQL> begin
  2  dbms_scheduler.create_schedule(
schedule_name  => 'INTERVAL_EVERY_1_SECONDS',
  start_date    => trunc(sysdate),
  repeat_interval => 'freq=SECONDLY;interval=1',
  comments     => 'Runtime: Every day all 1 SECONDS');  3    4    5    6  
  7  end;
  8  /

PL/SQL procedure successfully completed.

1초에 한번씩 수행할 Schedule을 생성합니다 

SQL> begin
dbms_scheduler.create_program
(program_name=> 'TEST_PROC01',
 program_type=> 'STORED_PROCEDURE',
 program_action=> 'SYS.TEST_PROC',
 enabled=>true,
 comments=>'job interval test'
 );
end;
PL/SQL procedure successfully completed.

수행할 Program을 생성합니다. 
TEST_PROC는 test table에 sysdate를 입력하는 procedure 입니다.

SQL> begin
dbms_scheduler.create_job
 (job_name => 'JOB_TEST',
  program_name=> 'TEST_PROC01',
  schedule_name=>'INTERVAL_EVERY_1_SECONDS',
  enabled=>true,
  auto_drop=>false,
  comments=>'job test');
end;
/  
PL/SQL procedure successfully completed.

이제 먼저 생성한 schedule과 program을 이용해 JOB을 생성합니다 

SQL> begin
dbms_scheduler.run_job('JOB_TEST',TRUE);
end; 
/
PL/SQL procedure successfully completed.



SQL> select * from test;

COMMIT_DATE
-------------------
2010/10/12 17:12:38
2010/10/12 17:12:39
2010/10/12 17:12:40
2010/10/12 17:12:41
2010/10/12 17:12:42
2010/10/12 17:12:43
2010/10/12 17:12:44
2010/10/12 17:12:45
2010/10/12 17:12:46
2010/10/12 17:12:47
2010/10/12 17:12:48
2010/10/12 17:12:49
2010/10/12 17:12:50
2010/10/12 17:12:51
2010/10/12 17:12:52
2010/10/12 17:12:53
2010/10/12 17:12:54
2010/10/12 17:12:55
2010/10/12 17:12:55
2010/10/12 17:12:56
2010/10/12 17:12:57
2010/10/12 17:12:58
2010/10/12 17:12:59
2010/10/12 17:13:00
2010/10/12 17:13:01
...

table에 들어간 데이터를 보니 1초에 한번씩 수행하고 있군요.. 

DBMS_JOB을 이용한 job은 interval에 제한이 있는 걸까요? 그런 자료는 못 본것 같은데..

예전 oracle 8에서 job_queue_interval parameter가 있을때
수행 시간이 job_queue_interval 주기때문에 job interval이 정확히 계산되지 않았던 것 같은데... 
혹시 job_queue_process가 wake-up 하는 시간때문일까요?  






10. 10. 6 작성자: Laurent Schneider의 Laurent Schneider

Pretty straightforward, check if dbms_transaction.step_id is null!

SQL> select dbms_transaction.step_id from dual;
        STEP_ID
---------------

SQL> insert into t values (1);
1 row created.

SQL> select dbms_transaction.step_id from dual;
        STEP_ID
---------------
114352430549782

SQL> commit;
Commit complete.

SQL> select dbms_transaction.step_id from dual;
        STEP_ID
---------------


STEP_ID가 어떤의미일까요?
메뉴얼엔 step_id function에 대해 아래와 같이 정의도어 있는데, 무슨 말인지 잘 모르겠네요. 

"This function returns local (to local transaction) unique positive integer that orders the DML operations of a transaction."

테스트를 해보자면...

SQL> delete from yhcho_temp where col1 = 'TURNER';
1 row deleted.

SQL> select dbms_transaction.step_id from dual;
                   STEP_ID
--------------------------
         37783619732783637

SQL> savepoint A ;
Savepoint created.

SQL> delete from yhcho_temp where col1 = 'KING';
1 row deleted.

SQL> select dbms_transaction.step_id from dual;
                   STEP_ID
--------------------------
         37783619732783639

SQL> rollback to savepoint A;
Rollback complete.

SQL> select dbms_transaction.step_id from dual;
                   STEP_ID
--------------------------
         37783619732783639

savepoint A까지 rollback 해도 step_id는 바뀌지 않는 군요.. 
단순히 transaction step에 대한 sequence 일까요? 

SQL> delete from yhcho_temp where col1 = 'KING';
1 row deleted.

SQL> select dbms_transaction.step_id from dual;
                   STEP_ID
--------------------------
         37783619732783641

특정 transaction을 가리키는 것 같진 않고 
위의 post 처럼 step_id로는 단순히 transaction이 있는지 여부만 확인할 수 있을 것 같네요..

SQL> desc dbms_transaction        
PROCEDURE ADVISE_COMMIT
PROCEDURE ADVISE_NOTHING
PROCEDURE ADVISE_ROLLBACK
PROCEDURE BEGIN_DISCRETE_TRANSACTION
PROCEDURE COMMIT
PROCEDURE COMMIT_COMMENT
 Argument Name                  Type                    In/Out Default?
 ------------------------------ ----------------------- ------ --------
 CMNT                           VARCHAR2                IN
PROCEDURE COMMIT_FORCE
 Argument Name                  Type                    In/Out Default?
 ------------------------------ ----------------------- ------ --------
 XID                            VARCHAR2                IN
 SCN                            VARCHAR2                IN     DEFAULT
FUNCTION LOCAL_TRANSACTION_ID RETURNS VARCHAR2
 Argument Name                  Type                    In/Out Default?
 ------------------------------ ----------------------- ------ --------
 CREATE_TRANSACTION             BOOLEAN                 IN     DEFAULT
PROCEDURE PURGE_LOST_DB_ENTRY
 Argument Name                  Type                    In/Out Default?
 ------------------------------ ----------------------- ------ --------
 XID                            VARCHAR2                IN
PROCEDURE PURGE_MIXED
 Argument Name                  Type                    In/Out Default?
 ------------------------------ ----------------------- ------ --------
 XID                            VARCHAR2                IN
PROCEDURE READ_ONLY
PROCEDURE READ_WRITE
PROCEDURE ROLLBACK
PROCEDURE ROLLBACK_FORCE
 Argument Name                  Type                    In/Out Default?
 ------------------------------ ----------------------- ------ --------
 XID                            VARCHAR2                IN
PROCEDURE ROLLBACK_SAVEPOINT
 Argument Name                  Type                    In/Out Default?
 ------------------------------ ----------------------- ------ --------
 SAVEPT                         VARCHAR2                IN
PROCEDURE SAVEPOINT
 Argument Name                  Type                    In/Out Default?
 ------------------------------ ----------------------- ------ --------
 SAVEPT                         VARCHAR2                IN
FUNCTION STEP_ID RETURNS NUMBER
PROCEDURE USE_ROLLBACK_SEGMENT
 Argument Name                  Type                    In/Out Default?
 ------------------------------ ----------------------- ------ --------
 RB_NAME                        VARCHAR2                IN



10. 8. 16 작성자: April C Sims의 Oracle High Availability

New error logging facility in 11g…spool errors from a table that traps them. Table is automatically created after using the SET command in SQLPLUS.

Data stored in the sperrorlog persists between sessions and whether it is interactive or non-interactive such as a script.

Should you turn on errorlogging for SYS?  Sort of a catchall auditing for errors not ordinarily trapped? I am turning on sperrorlog for SYS in a non-production 11gR2 database to see what happens.

New 11g SQLPLUS Parameter ERRORLOGGING [ID 471066.1]


11g에서는 sqlplus에서 발생하는 에러를 logging 할 수 있다는 군요. 
(이 사람들은 새로운 버전 나올때 마다 모든 메뉴얼을 다 보는 것일까요? 존경스럽습니다.. )

위의 내용보고 따라해 봤습니다..

$ sqlplus system
SQL> set errorlogging on
SQL> select * from sperrorlog;

no rows selected

SQL> select * from scott.emp;
select * from scott.emp
                    *
ERROR at line 1:
ORA-00942: table or view does not exist

SQL> set pagesize 200
SQL> select * from sperrorlog;

USERNAME
--------------------------------------------------------------------------------
TIMESTAMP
---------------------------------------------------------------------------
SCRIPT
--------------------------------------------------------------------------------
IDENTIFIER
--------------------------------------------------------------------------------
MESSAGE
--------------------------------------------------------------------------------
STATEMENT
--------------------------------------------------------------------------------
SYSTEM
2010-09-17-13.53.55.000000


ORA-00942: table or view does not exist
select * from scott.emp

잘 되는 군요..
sqlplus를 재 접속해도 위의 에러정보는 계속 남습니다. 

그러면 purge는 어떻게 할까요? 
따로 나와있는 내용이 없는 거 같으니, 아마 delete나 truncate로 해야하는 거 같긴한데..
요건 좀 나중에 확인해 보고..

user가 table을 만들고 이걸 지정할 수 도 있답니다. 

SQL>  SET ERRORLOGGING ON TABLE enduser_sperrorlog;

위의 블로그 한번 들러 보시지요~ ^^

사용자 table 데이터 중에서 꼭 변경되면 안되는 데이터는 반드시 있기마련입니다. 
예를 들자면, 이름과 주민등록 번호, 학생과 학번, 등등..

위의 데이터 처럼 입력은 가능해야 하나 한번 입력된 특정 column을 변경되지 않게 하기 위해서는 어떤 방법이 있을까요? 
가장 쉽게 생각할 수 있는게 trigger 입니다. 
다음은 trigger를 이용해 특정 column을 변경하지 못하게 설정하는 trigger sample 입니다. 

(사실 trigger 이외에 딱히 생각나는 방법이 없네요 --;)

1. SCOTT user의 EMP table에 trigger를 설정합니다. 

CREATE TRIGGER emp_upd_trigger
BEFORE UPDATE on emp
declare
    v_error VARCHAR2(256);
begin
    if (updating('EMPNO') or updating('ENAME'))
     then
         v_error:='You cannot update the empno';
         raise_application_error (-20999,v_error);
     end if;
end;
/

2. trigger가 만들어 졌으면 간단히 테스트를 해볼까요? 

SQL> select * from emp;

     EMPNO ENAME                          JOB                                MGR HIREDATE          SAL       COMM     DEPTNO
---------- ------------------------------ --------------------------- ---------- ---------- ---------- ---------- ----------
      7900 JAMES                          CLERK                             7698 1981-12-03        950                    30
      7902 FORD                           ANALYST                           7566 1981-12-03       3000                    20
      7934 MILLER                         CLERK                             7782 1982-01-23       1300                    10

SQL> update emp set empno = 9999 where ename = 'MILLER';
update emp set empno = 9999 where ename = 'MILLER'
       *
ERROR at line 1:
ORA-20999: You cannot update the empno or ename
ORA-06512: at "SCOTT.EMP_UPD_TRIGGER", line 7
ORA-04088: error during execution of trigger 'SCOTT.EMP_UPD_TRIGGER'

SQL> update emp set ename = 'ORACLE' where empno = 7934;
update emp set ename = 'ORACLE' where empno = 7934
       *
ERROR at line 1:
ORA-20999: You cannot update the empno or ename
ORA-06512: at "SCOTT.EMP_UPD_TRIGGER", line 7
ORA-04088: error during execution of trigger 'SCOTT.EMP_UPD_TRIGGER'

이 방법 이외에 다른 방법 아시는 분.. 
좀 알려주세요.. ^^


* 여기저기서 좋다는 책 몇권 추천합니다. 고수가 되는 그날까지.. 파이팅!!




We promised in an earlier post to cover some of the questions from the Optimizer round table discussion at Oracle Open World. Here's our first in a series of posts that will address these questions. 

Q: When moving from 10g to 11g, should hints in existing SQL be removed? 

A: I was glad to see this question at the round table, since I think this is something people often overlook when adding hints to an application. Over time, hints can become stale. You may have added a hint to a query because of a weakness in an old version of the optimizer, but the hint might no longer be necessary to get the best plan. Even worse, the hint may force a plan which is suboptimal, for a couple of reasons:

이 질문은 오라클 데이터베이스 관계자라면 매우 자주 듣는 질문이죠. 
이전 버전의 SQL에 적용된 hint를 제거하는게 맞을까요? 아님 계속 사용하는게 맞을까요? 
물론 답은 당연히 제거하라 겠죠? 

새로운 버전에서, 그리고 변경되는 데이터 상에서 해당 hint가 적정할지,
또 hint를 사용한 사람이 선택한 plan이 과연 적정할지.. 
그 hint는 새로운 버전에서 계속 존재하는지..
이러한 판단이 가능한 사람이 있을까 모르겠네요.. 

위의 포스트는 오라클 optimizer 팀 blog의 post 입니다. open world에서 질문 나온걸 정리한다네요. 
한번 읽어 보세요 ~
baseline을 이용한 plan 고정하는 방법도 나오네요..

그나저나 _optimizer_ignore_hints parameter는 언제 생긴걸까? 
이거 쓸만할 거 같은데, 확인 좀 해 봐야겠네요~


* 여기저기서 좋다는 책 몇권 추천합니다. 고수가 되는 그날까지.. 파이팅!!



이 자료는 O'Reilly에서 나온 " Mastering Oracle SQL, 2nd Edition"을 공부하면서 몰랐던 부분을 정리하고 있습니다. 
"Mastering Oracle SQL, 2nd Edition"의 저자는 Alan Beaulieu, Sanjay Mishra 이며 2004년에 나온 책이네요. 
알라딘에서 구해 볼 수 있습니다. 

HAVING 절은 항상 쓰면서 따로 메뉴얼을 읽어본적은 없다.
그래서 아마 group 함수의 결과에 대해 조건을 주는거? 이렇게 생각하고 있었는데, 
역시 메뉴얼을 읽어야해 ~ 

HAVING 절은 GROUP BY 절에 의해 나오는 나올수 있는 결과에 대해 filtering 해주는 역활을 해준다. 
즉 내가 지금까지 생각하던 거와는 달리 
group 함수의 결과 컬럼에 대해서만 조건을 주는 게 아니라 
결과 SET group by 절에 의해 나올 수 있는 결과 set 에 대해 조건을 줄 수 있다. 

다음의 예를 보면 .. 
부서별 인원수를 구하는 SQL이다.
SQL> select deptno,count(*) from emp group by deptno;

    DEPTNO   COUNT(*)
---------- ----------
        30          6
        20          5
        10          3

이 중인 인원수가 4이상인 부서를 출력한다. 즉 group 함수에 의해 계산된 값에 대한 조건이다. 
SQL> select deptno,count(*) from emp group by deptno having count(*) > 4;

    DEPTNO   COUNT(*)
---------- ----------
        30          6
        20          5

아래의 SQL은 group by 에 의해 만들어진 결과에서 deptno가 20 이상인 부서만 출력한다. 
SQL> select deptno,count(*) from emp group by deptno having deptno > 20;

    DEPTNO   COUNT(*)
---------- ----------
        30          6

그러면 group by 절에 의한 결과에 대한 having과 select 절의 where 절은 바꿔 쓸 수 있을까?
아래의 결과를 보면 having deptno > 20 과 where deptno > 20의 결과는 같다. (당연한가?)

SQL> select deptno,count(*) from emp where deptno > 20 group by deptno;

    DEPTNO   COUNT(*)
---------- ----------
        30          6

그러나 having 절에 의한 조건은 filter 처리로 계산된 결과에서 특정 조건만을 걸러내고 있으나, 
where 절의 경우 access 처리로 scan의 범위를 줄이고 있음을 알 수 있다. 

SQL> select deptno,count(*) from emp group by deptno having deptno > 20;

------------------------------------------------------------------------------------
| Id  | Operation              | Name      | Rows  | Bytes | Cost (%CPU)| Time     |
------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT       |           |     2 |     6 |     3  (34)| 00:00:01 |
|*  1 |  FILTER                |           |       |       |            |          |
|   2 |   HASH GROUP BY        |           |     2 |     6 |     3  (34)| 00:00:01 |
|   3 |    INDEX FAST FULL SCAN| EMP_IDX04 |   449 |  1347 |     2   (0)| 00:00:01 |
------------------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------
   1 - filter("DEPTNO">20)

SQL> select deptno,count(*) from emp where deptno > 20 group by deptno;

----------------------------------------------------------------------------------
| Id  | Operation            | Name      | Rows  | Bytes | Cost (%CPU)| Time     |
----------------------------------------------------------------------------------
|   0 | SELECT STATEMENT     |           |     2 |     6 |     1   (0)| 00:00:01 |
|   1 |  SORT GROUP BY NOSORT|           |     2 |     6 |     1   (0)| 00:00:01 |
|*  2 |   INDEX RANGE SCAN   | EMP_IDX03 |   193 |   579 |     1   (0)| 00:00:01 |
----------------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------
   2 - access("DEPTNO">20)

queyr의 결과는 동일하나 access 하는 범위 자체가 틀리니 이에 대한 주의가 필요하다. 
당연히 access 범위를 줄일 수 있는 조건은 where 절에 기술하는 것이 유리할 듯 !!

근데, 테스트 하다보니 아래처럼 수행해도 결과가 잘 나오더군요. 
select는 count를 했으나 having에는 sum으로 조건을 주어도 결과가 잘 나오네요. 

SQL> select deptno,count(*) from emp group by deptno having sum(sal) > 10000;

    DEPTNO   COUNT(*)
---------- ----------
        20          5

Execution Plan
----------------------------------------------------------
Plan hash value: 3110987654

----------------------------------------------------------------------------
| Id  | Operation           | Name | Rows  | Bytes | Cost (%CPU)| Time     |
----------------------------------------------------------------------------
|   0 | SELECT STATEMENT    |      |     4 |    28 |    13   (8)| 00:00:01 |
|*  1 |  FILTER             |      |       |       |            |          |
|   2 |   HASH GROUP BY     |      |     4 |    28 |    13   (8)| 00:00:01 |
|   3 |    TABLE ACCESS FULL| EMP  |   449 |  3143 |    12   (0)| 00:00:01 |
----------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------
   1 - filter(SUM("SAL")>10000)

그럼 group by에 의한 수행 결과에 대해 조건을 주는 것이 아니라 
group by에 의해 나올 수 있는 결과에 대해 조건을 줄 수 있다는 거군요..

count(*)와 sum(sal)은 operation 자체가 다른데, 이걸 다 계산하고 있다는 건가? 
아니면 having에 있는 sum()이 query 수행시 참조되는 건가? 

"The HAVING clause is closely associated with the GROUP BY clause. The HAVING clause is used to put a filter on the groups created by the GROUP BY clause. If a query has a HAVING clause along with a GROUP BY clause, the result set will include only the groups that satisfy the condition specified in the HAVING clause."

네, having 절에 있는 group operation도 참조되는 게 맞습니다.. ^^

SQL> select deptno from emp group by deptno having sum(sal) > 10000;

    DEPTNO
----------
        20



* 여기저기서 좋다는 책 몇권 추천합니다. 고수가 되는 그날까지.. 파이팅!!



이 자료는 O'Reilly에서 나온 " Mastering Oracle SQL, 2nd Edition"을 공부하면서 몰랐던 부분만을 정리하고 있습니다.
"Mastering Oracle SQL, 2nd Edition"의 저자는 Alan Beaulieu, Sanjay Mishra 이며 2004년에 나온 책이네요. 
알라딘에서 구해 볼 수 있습니다. 

Oracle GROUP 함수는 다중 사용을 지원한다. 몰랐다...
간단히 말하면 GROUP 함수 안에 GROUP 함수를 사용할 수 있다. 

예를 들자면 ..

부서별 연봉 합계이다. 
SQL> select deptno,sum(sal) from emp group by deptno;

    DEPTNO   SUM(SAL)
---------- ----------
        30       9400
        20      10875
        10       8750

이 연봉 합계가 가장 높은 연봉 합은 다음처럼 구할 수 있다..

SQL> select max(salary) from (
SQL> select deptno,sum(sal) salary from emp group by deptno;

MAX(SALARY)
-----------
      10875

이걸 중첩 GROUP operation을 쓰면 다음과 같이 쓰일 수 있다. 

SQL> select max(sum(sal)) from emp group by deptno;

MAX(SUM(SAL))
-------------
        10875

SQL> select max(sum(sal)),min(sum(sal)),avg(sum(sal)) from emp group by deptno;

MAX(SUM(SAL)) MIN(SUM(SAL)) AVG(SUM(SAL))
------------- ------------- -------------
        10875          8750          9675

그럼 중첩 GROUP operation은 몇개까지 중첩될 수 있을까? 
아래 SQL이 어떤 의미인지는 모르겠지만..

일단 3개 중첩!!

SQL> select max(sum(count(sal))) from emp group by deptno;
select max(sum(count(sal))) from emp group by deptno
               *
ERROR at line 1:
ORA-00935: group function is nested too deeply

SQL> !oerr ora 935
00935, 00000, "group function is nested too deeply"
// *Cause:
// *Action:

GROUP function에 dept의 제한이 있는게 확인 된다. 
그럼 SUBQUERY를 사용하게 되면.. 

SQL> select max(a) from (
SQL>   select sum(b) a from  (
SQL>    select count(sal) b from emp group by deptno ));

    MAX(A)
----------
        14

잘 되는 군요.

다들 아시는 내용이겠지만, 저는 몰랐기 때문에 정리합니다 
-,.-



* 여기저기서 좋다는 책 몇권 추천합니다. 고수가 되는 그날까지.. 파이팅!!



보통, Test 시스템에서 가동 시스템으로 데이타를 이관하는 경우, 데이타 뿐만 아니라 통계정보도 이관하여, Test계와 가동계를 동일하게 유지하고자 하는 경우가 있읍니다. 이러한 경우,데이타는 쉽게 옮겨도 통계치는 딱히 옮기는 방법이 없습니다. 이때 아래의 방법을 사용하시면 쉽게 올길수 있읍니다.

dbms_stats.export_table_stats(
ownname   VARCHAR2,                -- schema name
tabname   VARCHAR2,                -- table name
partname  VARCHAR2 DEFAULT NULL,   -- partition name
stattab   VARCHAR2,                -- stat table name
statid    VARCHAR2 DEFAULT NULL,   -- optional identifier
cascade   BOOLEAN  DEFAULT TRUE,   -- TRUE = indexes too
statown   VARCHAR2  DEFAULT NULL); -- stat table schema

exec dbms_stats.export_table_stats(USER, 'servers', NULL, 'STAT_TAB', NULL, TRUE);

dbms_stats.import_table_stats(
ownname       VARCHAR2,
tabname       VARCHAR2,
partname      VARCHAR2 DEFAULT NULL,
stattab       VARCHAR2,
statid        VARCHAR2 DEFAULT NULL,
cascade       BOOLEAN  DEFAULT TRUE,
statown       VARCHAR2 DEFAULT NULL,
no_invalidate BOOLEAN  DEFAULT to_no_invalidate_type(get_param('NO_INVALIDATE')),
force         BOOLEAN DEFAULT FALSE);

exec dbms_stats.import_table_stats(USER, 'servers', stattab=>'STAT_TAB');

예 : SCOTT의 EMP  통계를 SCOTT2의 EMP2로 이관

1. 통계정보를 임시로 저장할 Table생성.
SQL> exec dbms_stats.create_stat_table('SCOTT','STATS');

2. 원하는 table의 통계정보를 임시 table로 이관.
SQL> exec dbms_stats.export_table_stats('SCOTT','EMP',NULL,'STATS','emp stats',TRUE);

* 참고 (updated: 2010/08/03)
"emp stats"로 중간에 space가 들어가니 에러가 나는 군요.. 이래서 직접 테스트를해봐야 한다니까...

SQL> exec dbms_stats.export_table_stats('SCOTT','EMP',NULL,'STATS','EMP_STATS',TRUE,'SCOTT');

BEGIN dbms_stats.export_table_stats('SCOTT','EMP',NULL,'STATS','EMP STATS',TRUE,'SCOTT'); END;
*
ERROR at line 1:
ORA-20001: EMP STATS is an invalid identifier
ORA-06512: at "SYS.DBMS_STATS", line 8240
ORA-06512: at "SYS.DBMS_STATS", line 9188
ORA-06512: at line 1

* 주의 (updated: 2010/08/03)
STATS table의 데이터를 qery 해보면 EMP table의 원래 소유자인 SCOTT이 C5 column에 명시되어 있습니다. 만약 다른 계정으로, 즉 SCOTT2 계정으로 통계정보를 옮기려면 STATS table의 SCOTT값을 SCOTT2로 update 해주어야 합니다. 
두개의 DB의 계정이 동일하다면 변경해 줄 필요는 없겠죠~


3. 임시 table을 export, 그리고 target db로 import.
 $exp scott/tiger tables=STATS file=expstat.dmp
 $imp scott/tiger file=expstat.dmp full=y log=implog.txt
(만약 동일 DB라면 이 과정은 생략 가능합니다.)

4. 임시 Table로 부터 통계치를 원하는 table에 넣는다.
SQL> exec dbms_stats.import_table_stats('SCOTT2','EMP2',NULL,'STATS');





기본적으로 recovery는 backup된 datafile을 가져다 놓고 backup 시점 이후의 archive log를 적용하게 됩니다. 
complete recovery의 경우 모든 archive log가 적용된후 undo가 다시 적용되는데요..

아래의 시나리오는 backup된 datafile은 없으나, 손상된 datafile 생성 시점이후 모든 archive log가 있을 경우 recovery하는 시나리오입니다. 
예전 data guard에서는 primary DB에서 datafile 생성한게 standby에 생성되지 않아 수작업으로 'alter database create datafile,..'을 수행했던거 같은데, 요즘 version에서는 되는지 모르겠네요..

Re-Creating Datafiles When Backups Are Unavailable: Scenario


If a datafile is damaged and no backup of the file is available, then you can still recover the datafile if:

  • All archived log files written after the creation of the original datafile are available

  • The control file contains the name of the damaged file (that is, the control file is current, or is a backup taken after the damaged datafile was added to the database)

    Note:

    You cannot re-create any of the datafiles for the SYSTEM tablespace by using the CREATE DATAFILE clause of the ALTER DATABASE statement because the necessary redo is not available.

To re-create a datafile for recovery:

Create a new, empty datafile to replace a damaged datafile that has no corresponding backup. For example, assume that the datafile ?/oradata/trgt/users01.dbf has been damaged, and no backup is available. The following statement re-creates the original datafile (same size) on disk2:


ALTER DATABASE CREATE DATAFILE '?/oradata/trgt/users01.dbf' AS
                               '/disk2/users01.dbf';
손상된 '?/oradata/trgt/users01.dbf'를 '/disk2/users01.dbf'로 이름을 바꿔 빈 datafile을 생성합니다. 

This statement creates an empty file that is the same size as the lost file. The database looks at information in the control file and the data dictionary to obtain size information. The old datafile is renamed as the new datafile.

Perform media recovery on the empty datafile. For example, enter:


RECOVER DATAFILE '/disk2/users01.dbf';
새로 만들어진 빈 datafile에 대해 archive log를 complete로 적용합니다.

All archived logs written after the original datafile was created must be applied to the new, empty version of the lost datafile during recovery.




* 여기저기서 좋다는 책 몇권 추천합니다. 고수가 되는 그날까지.. 파이팅!!



+ INVISIBLE index 생성 
SQL> create index emp_idx01 on emp(empno) invisible;

Index created.

+ 일반 세션에서 SQL 수행 
SQL> set autot on exp
SQL> 
SQL> select empno from emp where empno = 7839;

     EMPNO
----------
      7839

Execution Plan
----------------------------------------------------------
Plan hash value: 2872589290

--------------------------------------------------------------------------
| Id  | Operation         | Name | Rows  | Bytes | Cost (%CPU)| Time     |
--------------------------------------------------------------------------
|   0 | SELECT STATEMENT  |      |     1 |     4 |    12   (0)| 00:00:01 |
|*  1 |  TABLE ACCESS FULL| EMP  |     1 |     4 |    12   (0)| 00:00:01 |
--------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   1 - filter("EMPNO"=7839)

+ INVISIBLE INDEX 사용 정의
SQL> alter session set optimizer_use_invisible_indexes=true;

Session altered.

SQL> select empno from emp where empno = 7839;

     EMPNO
----------
      7839


Execution Plan
----------------------------------------------------------
Plan hash value: 3956893595

------------------------------------------------------------------------------
| Id  | Operation        | Name      | Rows  | Bytes | Cost (%CPU)| Time     |
------------------------------------------------------------------------------
|   0 | SELECT STATEMENT |           |     1 |     4 |     1   (0)| 00:00:01 |
|*  1 |  INDEX RANGE SCAN| EMP_IDX01 |     1 |     4 |     1   (0)| 00:00:01 |
------------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   1 - access("EMPNO"=7839)

+ INVISIBLE INDEX 사용 해제
SQL> alter session set optimizer_use_invisible_indexes=false;

Session altered.

SQL> select empno from emp where empno = 7839;

     EMPNO
----------
      7839


Execution Plan
----------------------------------------------------------
Plan hash value: 2872589290

--------------------------------------------------------------------------
| Id  | Operation         | Name | Rows  | Bytes | Cost (%CPU)| Time     |
--------------------------------------------------------------------------
|   0 | SELECT STATEMENT  |      |     1 |     4 |    12   (0)| 00:00:01 |
|*  1 |  TABLE ACCESS FULL| EMP  |     1 |     4 |    12   (0)| 00:00:01 |
--------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   1 - filter("EMPNO"=7839)

+ OPT_PARAM hint를 통한 INVISIBLE index 사용 권한 부여 -> 실패 ?
SQL> select /*+ opt_param('optimizer_use_invisible_indexes','true') */ empno from emp where empno = 7839;

     EMPNO
----------
      7839


Execution Plan
----------------------------------------------------------
Plan hash value: 2872589290

--------------------------------------------------------------------------
| Id  | Operation         | Name | Rows  | Bytes | Cost (%CPU)| Time     |
--------------------------------------------------------------------------
|   0 | SELECT STATEMENT  |      |     1 |     4 |    12   (0)| 00:00:01 |
|*  1 |  TABLE ACCESS FULL| EMP  |     1 |     4 |    12   (0)| 00:00:01 |
--------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   1 - filter("EMPNO"=7839)

oracle 10g R2 new feature를 보다 보니까.. (나온지가 언젠데.!!)
"restore point"라는 개념이 나오더군요.. (아래..)

테스트 함 해봤습니다.

원문 : Restore Point in Flashback Database

SQL의 savepoint라는 개념을 기억하십니까? 트랜잭션에서 savepoint를 생성한 후, 데이터를 일부 수정한 다음, 다시 savepoint를 생성하는 식으로 작업합니다. 그리고 변경된 내용을 다시 되돌리고 싶다면, 해당되는 savepoint로 롤백하면 됩니다.

Oracle Database 10g의 Flashback Database는 데이터베이스를 과거의 특정 시점으로 되돌리는 기능을 제공합니다. 그렇다면 여기에도 savepoint와 유사한 개념을 도입하면 유용하지 않을까요? 시간을 기준으로 하지 않고, 명명된 시점(named point)으로 되돌릴 수 있게 하면 좋지 않을까요?

Oracle Database 10g Release 2에 추가된 “restore point”라는 기능이 바로 이러한 역할을 담당합니다. 그 작동 원리가 다음과 같습니다.


위의 내용은 OTN의
 Oracle Database 10g Release 2의 신기능에서 가져왔습니다.

1. RESTORE POINT 생성.

SQL> create restore point before_fb_test guarantee flashback database;

ERROR at line 1:
ORA-38784: Cannot create restore point 'BEFORE_FB_TEST'.
ORA-38786: Flash recovery area is not enabled.

SQL> alter system set db_recovery_file_dest='/..' scope=both;
SQL> alter system set log_archive_dest_1='' scope=spfile;
SQL> shutdown immediate;
SQL> startup

SQL> archive log list
Database log mode   Archive Mode
Automatic archival  Enabled
Archive destination USE_DB_RECOVERY_FILE_DEST
            :


SQL> create restore point before_fb_test guarantee flashback database;

ERROR at line 1:
ORA-38784: Cannot create restore point 'BEFORE_FB_TEST'.
ORA-38787: Creating the first guaranteed restore point requires mount mode when flashback database is off.

ORA-38787: Creating the first guaranteed restore point requires mount mode when flashback database is off.
Cause: While flashback database is not on, an attempt was made to create the first guaranteed restore point while the database is open.
Action: Mount the database and retry.

SQL> shutdown immediate;
SQL> STARTUP MOUNT
SQL> ALTER DATABASE FLASHBACK ON;

ERROR at line 1:
ORA-38706: Cannot turn on FLASHBACK DATABASE logging.
ORA-38708: Not enough space for first flashback database log file

SQL> alter system set db_recovery_file_dest_size=5G scope=both;
SQL> ALTER DATABASE FLASHBACK ON;
SQL> ALTER DATABASE OPEN;

( flash backup area에 flb라는 확장자로 파일이 하나 생기는 군요.)

SQL> create restore point before_fb_test guarantee flashback database;

2. 테스트

SQL> delete from scott.emp;
SQL> commit;

* flash backup area에 flb file이 추가로 1개 더 생기는 ..

SQL> SHUTDOWN IMMEDIATE
SQL> STARTUP MOUNT
SQL> FLASHBACK DATABASE TO RESTORE POINT before_update_of_emp;
SQL> ALTER DATABASE OPEN RESETLOGS;

기본 설정만 해놓으면 잘 되는 거 같네요..



+ Recent posts