블로그 이미지
redkite

카테고리

분류 전체보기 (291)
00.SI프로젝트 산출물 (0)
00.센터 운영 문서 (0)
01.DBMS ============.. (0)
01.오라클 (117)
001.DB 관리 (19)
002.DB 마이그레이션 (8)
003.DB 백업 및 복구 (20)
004.DB 보안 (8)
005.DB 설치 (7)
006.DB 스크립트 (0)
007.DB Knowledge Bas.. (38)
008.DB 통계 및 공간 관리 (3)
009.DB Trouble Shoot.. (14)
010.교육자료 (0)
999.테스트 (0)
01.MS-SQL (15)
01.MySQL (30)
01.PostgreSql (0)
01.DB튜닝 (28)
====================.. (0)
02.SERVER ==========.. (0)
02.서버-공통 (11)
02.서버-Linux (58)
02.서버-Unix (12)
02.서버-Windows (2)
====================.. (0)
03.APPLICATION =====.. (11)
====================.. (0)
04.ETC =============.. (0)
04.보안 (5)
====================.. (0)
05.개인자료 (1)
06.캠핑관련 (0)
07.OA관련 (1)
Total
Today
Yesterday

달력

« » 2024.5
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31

공지사항

최근에 올라온 글

2 Oracle and MySQL Compared

This chapter compares the MySQL database and the Oracle database. It includes the following sections:

2.1 Database Security

This section includes information about security issues with MySQL databases and Oracle databases.

As with Oracle, MySQL users are maintained by the database. MySQL uses a set of grant tables to keep track of users and the privileges that they can have. MySQL uses these grant tables when performing authentication, authorization and access control for users.

2.1.1 Database Authentication

Unlike Oracle (when set up to use database authentication) and most other databases that use only the user name and password to authenticate a user, MySQL uses an additional location parameter when authenticating a user. This location parameter is usually the host name, IP address, or a wildcard (Ò%Ó). With this additional parameter, MySQL may further restrict a user access to the database to a particular host or hosts in a domain. Moreover, this also allows a different password and set of privileges to be enforced for a user depending on the host from which the connection is made. Thus, user scott, who logs on from abc.com may or may not the same as user scott who logs on from xyz.com.

2.1.2 Privileges

The MySQL privilege system is a hierarchical system that works through inheritance. Privileges granted at a higher level are implicitly passed down to all lower levels and may be overridden by the same privileges set at lower levels. MySQL allows privileges to be granted at five different levels, in descending order of the scope of the privileges:

  • Global

  • Per-host basis

  • Database-level

  • Table-specific

  • Column-specific (single column in a single table

Each level has a corresponding grant table in the database. When performing a privilege check, MySQL checks each of the tables in descending order of the scope of the privileges, and the privileges granted at a lower level take precedence over the same privileges granted at a higher level.

The privileges supported by MySQL are grouped into two types: administrative privileges and per-object privileges. The administrative privileges are global privileges that have server-wide effects and are concerned with the functioning of MySQL. These administrative privileges include the FILE, PROCESS, REPLICATION, SHUTDOWN and SUPER privilege. The per-object privileges affect database objects such tables, columns, indexes, and stored procedures, and can be granted with a different scope. These per-object privileges are named after the SQL queries that trigger their checks.

Unlike in Oracle, there is no concept of role in MySQL. Thus, in order to grant a group of users the same set of privileges, the privileges have to be granted to each user separately. Alternately, though less satisfactory for auditing, users performing tasks as a role may all share a single user account that is designated for the "role" and with the required privileges granted.

2.2 Schema Migration

The schema contains the definitions of the tables, views, indexes, users, constraints, stored procedures, triggers, and other database-specific objects. Most relational databases work with similar objects.

This section contains the following:

2.2.1 Schema Object Similarities

There are many similarities between schema objects in Oracle and MySQL. However, some schema objects differ between these databases. For more information about schema objects, see Oracle SQL Reference.

Table 2-1 shows the differences between Oracle and MySQL.

Table 2-1 Schema Objects in Oracle and MySQL

OracleMySQL

AFTER trigger

trigger

BEFORE trigger

trigger

Check constraint

Check constraint

Column default

Column default

Database

Database

Foreign key

Foreign key

Index

Index

Package

N/A

PL/SQL function

Routine

PL/SQL procedure

Routine

Primary key

Primary key

Role

N/A

Schema

Schema

Sequence

AUTO_INCREMENT for a column

Snapshot

N/A

Synonym

N/A

Table

Table

Tablespace

N/A

Temporary table

Temporary table

Trigger for each row

Trigger for each row

Unique key

Unique key

User

User

View

View


2.2.2 Schema Object Names

Oracle is case insensitive to object names, and Oracle schema object names are stored as uppercase.

As in Oracle, column, index, stored procedure, and trigger names as well as column aliases in MySQL are case insensitive on all platforms. However, the case sensitivity of database and tables names for MySQL differs from Oracle. In MySQL, databases correspond to directories within the data directory, and tables correspond to one or more files within the database directory. As such, the case sensitivity of the database and table names is determined by the case sensitivity of the underlying operating systems. This means that database and table names are not case-sensitive in Windows and are case-sensitive in most varieties of Unix. However, MySQL allows users to determine how the database and table names are stored on disk and in their use in MySQL through the lower_case_table_names system variable. Table aliases are case-sensitive in releases before MySQL 4.1.1.

Both Oracle and MySQL let you use reserved words as object names by representing the name with a quoted identifier. However, MySQL allows some reserved words such as DATE and TIMESTAMP to be used as unquoted identifier for object names, although this is not allowed in Oracle. SQL Developer appends an underscore (_) to the name of a MySQL object that is an Oracle reserved word.

MySQL and Oracle have some minor differences in their definition of an identifier. In MySQL, an unquoted identifier may begin with a digit, and double quotation marks are allowed in a quoted identifier; however, neither of these is allowed in an Oracle identifier. In MySQL, the quote character is the backtick (`). If the SQL mode ANSI_QUOTES is set, double quotes can also be used to quote the identifiers. In Oracle, identifiers are quoted using double quotation marks.

You should choose a schema object name that is unique by case and by at least one other characteristic, and ensure that the object name is not a reserved word from either database.

2.2.3 Table Design Considerations

This section discusses table design issues that you need to consider when converting MySQL databases to Oracle. This section includes the following­:

2.2.3.1 Character Data Types

MySQL and Oracle have some differences in the character types that they support and in the way they store and retrieve the character type values.

MySQL supports the CHAR and VARCHAR type for character type with a length that is less than 65,535 bytes. The CHAR type can have a maximum length of 255 bytes, and as of MySQL 3.23 it may also be declared with a length of 0 byte. Before MySQL 5.0.3, the length specification for the VARCHAR type is the same as the CHAR type. From MySQL 5.0.3 on, the maximum length for the VARCHAR type is 65,535 bytes. Oracle supports four character types: CHAR, NCHAR, NVARCHAR2 and VARCHAR2. The minimum length that can be declared for all Oracle character types is 1 byte. The maximum size allowed for CHAR and NCHAR is 2,000 bytes, and for NVARCHAR2 and VARCHAR2 it is 4,000 bytes.

MySQL CHAR values are right-padded with spaces to the specified length when they are stored, and trailing spaces are removed when the values are retrieved. On the other hand, VARCHAR values are stored using as many characters as are given, but before MySQL 5.0.3 trailing spaces are removed when the values are stored and retrieved. Oracle blank-pads the value for its CHAR and NCHAR type to the column length if the value is shorter than the column length, and trailing spaces are not removed on retrieval. For NVARCHAR2 and VARVHAR2 data type columns, Oracle stores and retrieves the value exactly as is given, including trailing spaces.

If a value is assigned to a character type column that exceeds its specified length, MySQL truncates the value and does not generate an error unless the STRICT SQL mode is set. Oracle generates an error if the value assigned to a character type column exceeds its specified length.

In MySQL, every character type (CHAR, VARCHAR, and TEXT) column has a column character set and collation. If the character set or collation is not explicitly defined in the column definition, the table character set or collation is implied if specified; otherwise, the database character or collation is chosen. In Oracle, the character set for CHAR and VARCHAR2 types is defined by the database character set, and for the character set for NCHAR and NVARCHAR types is defined the national character set.

When declaring a CHAR or VARCHAR type in MySQL, the default length semantics is characters instead of bytes for MySQL 4.1 and later. In Oracle, the default length semantics is bytes for CHAR and VARCHAR2 types and characters for NCHAR and NVARCHAR2 types.

SQL Developer will map MySQL CHAR and VARCHAR types to Oracle CHAR and VARCHAR2 types, respectively. SQL Developer will determine the maximum number of bytes for the Oracle CHAR and VARCHAR2 data type columns from the number of bytes required to hold the maximum length specified for the corresponding MySQL CHAR and VARCHAR data type columns. If the MySQL VARCHAR2 column is such that the data exceeds 4000 bytes, convert the column to an Oracle CLOB data type column.

2.2.3.2 Column Default Value

MySQL differs from Oracle in the way it handles default value for a column that does not allow NULL value.

In MySQL, for a column that does not allow NULL value and for which no data is provided for the column when data is inserted into the table, MySQL determines a default value for the column. This default value is the implicit default value for the column data type. However, if the strict mode is enabled, MySQL generates errors, and for transactional tables it rolls back the insert statement.

In Oracle, when data is inserted into a table, data must be provided for all columns that do not allow NULL value. Oracle does not generate a default value for columns that have the NOT NULL constraint.

2.2.4 Migrating Multiple Databases

SQL Developer supports the migration of multiple MySQL databases if they are on the same MySQL database server.

2.2.5 Schema Migration Considerations for MySQL

Schema migration considerations for MySQL apply in the following areas"

2.2.5.1 Databases

When migrating MySQL databases to Oracle, SQL Developer maps each MySQL database to a tablespace in Oracle. Database objects, such as tables, indexes and views are stored in the respective tablespaces and are referenced from the Oracle schema for the user that owns them.

2.2.5.2 Mapping MySQL Global and Database-Level Privileges to Oracle System Privileges

SQL Developer does not process all the administrative privileges on MySQL, except the SUPER privilege. Table 2-2 shows the mappings for MySQL per-object privileges granted at the different levels as well as the SUPER privilege granted at the global level.

Table 2-2 MySQL Privileges and Oracle System Privileges

LevelPrivilegeSystem Privilege(s) on Oracle

Global

ALTER

ALTER ANY TABLE, ALTER ANY SEQUENCE, ALTER ANY CUSTER, COMMENT ANY TABLE

Global

ALTER ROUTINE

ALTER ANY PROCEDURE, DROP ANY PROCEDURE

Global

CREATE

CREATE ANY TABLE, CREATE ANY SEQUENCE, CREATE ANY CLUSTER, CREATE DATABASE LINK, COMMENT ANY TABLE

Global

CREATE ROUTINE

CREATE ANY PROCEDURE

Global

CREATE USER

CREATE USER, GRANT ANY PRIVILEGE

Global

CREATE VIEW

CREATE ANY VIEW

Global

DELETE

ALTER ANY TABLE, DROP USER, DELETE ANY TABLE

Global

DROP

DROP ANT TABLE, DROP ANY SEQUENCE, DROP ANY CLUSTER, DROP ANY VIEW

Global

EXECUTE

EXECUTE ANY PROCEDURE

Global

INDEX

CREATE ANY INDEX, ALTER ANY INDEX, DROP ANY INDEX

Global

INSERT

INSERT ANY TABLE

Global

LOCK TABLES

LOCK ANY TABLE

Global

SELECT

SELECT ANY TABLE

Global

SUPER

CREATE ANY TRIGGER, DROP ANY TRIGGER

Global

UPDATE

UPDATE ANY TABLE

Global

USAGE

CREATE SESSION, ALTER SESSION, UNLIMITED TABLESPACE

Database

CREATE

CREATE CLUSTER, CREATE DATABASE LINK, CREATE SEQUENCE, CREATE TABLE

Database

CREATE ROUTINE

CREATE PROCEDURE

Database

CREATE VIEW

CREATE VIEW

Table

CREATE

CREATE TABLE

Table

CREATE VIEW

CREATE VIEW


2.2.5.3 Temporary Tables

SQL Developer does not support the migration of temporary tables.

In MySQL, temporary tables are database objects that are visible only to the current user session and are automatically dropped when the user session ends.

The definition of temporary tables in Oracle differs slightly from MySQL, in that the temporary tables, once created, exist until they are explicitly dropped and they are visible to all sessions with appropriate privileges. However, the data in the temporary tables is visible only to the user session that inserts the data into the table, and the data may persist for the duration of a transaction or a user session.

2.2.5.4 Owner of Schema Objects

SQL Developer creates an Oracle schema for the MySQL root user that owns, for all databases to be migrated, all database objects except stored procedures. For stored procedures, the MySQL users that created them remain the owner. SQL Developer creates an Oracle schema for each MySQL user that is migrated.

2.3 Data Types

This section describes the data types used within Oracle. It shows the MySQL data types and the Oracle equivalent. It includes information about the following:

2.3.1 Supported Oracle Data Types

Table 2-3 describes the Oracle data types supported by Oracle SQL Developer.

Table 2-3 Supported Oracle Data Types

Data TypeDescription

BLOB

A binary large object. Maximum size is 4 gigabytes.

CHAR (SIZE)

Fixed-length character data of length size bytes. Maximum size is 2000 bytes. Default and minimum size is 1 byte.

CLOB

A character large object containing single-byte characters. Both fixed-width and variable-width character sets are supported, both using the CHAR database character set. Maximum size is 4 gigabytes.

DATE

The DATE data type stores date and time information. Although date and time information can be represented in both CHAR and NUMBER data types, the DATE data type has special associated properties. For each DATE value, Oracle stores the following information: century, year, month, day, hour, minute, and second.

FLOAT

Specifies a floating-point number with decimal precision 38, or binary precision 126.

LONG (SIZE)

Character data of variable length up to 2 gigabytes, or 2^31 -1 bytes.

LONG RAW

Raw binary data of variable length up to 2 gigabytes.

NCHAR (SIZE)

Fixed-length character data of length size characters or bytes, depending on the choice of national character set. Maximum size is determined by the number of bytes required to store each character, with an upper limit of 2000 bytes. Default and minimum size is 1 character or 1 byte, depending on the character set.

NCLOB

A character large object containing multibyte characters. Both fixed-width and variable-width character sets are supported, both using the NCHAR database character set. Maximum size is 4 gigabytes. Stores national character set data.

NUMBER

Number having precision p and scale s. The precision p can range from 1 to 38. The scale s can range from -84 to 127.

NVARCHAR2 (SIZE)

Variable-length character string having maximum length size characters or bytes, depending on the choice of national character set. Maximum size is determined by the number of bytes required to store each character, with an upper limit of 4000 bytes. You must specify size for NVARCHAR2.

RAW (SIZE)

Raw binary data of length size bytes. Maximum size is 2000 bytes. You must specify size for a RAW value.

VARCHAR (SIZE)

The VARCHAR data type is currently synonymous with the VARCHAR2 data type. Oracle recommends that you use VARCHAR2 rather than VARCHAR. In the future, VARCHAR might be defined as a separate data type used for variable-length character strings compared with different comparison semantics. The maximum size is 4000 and the minimum of 1 is the default.

BINARY_DOUBLE

A 64-bit, double-precision floating-point number data type.

BINARY_FLOAT

A 32-bit, single-precision floating-point number data type.


For more information about Oracle data types, see Oracle Database SQL Language Reference.

2.3.2 Default Data Type Mappings

Table 2-4 shows the default settings used by SQL Developer to convert data types from MySQL to Oracle. SQL Developer enables you to change the default setting for certain data types by specifying an alternative type. For information about changing the default data type mappings, see the SQL Developer online help.

Table 2-4 Default Data Type Mappings Used by Oracle SQL Developer

MySQL Data TypeOracle Data Type

BIGINT

NUMBER(19, 0)

BIT

RAW

BLOB

BLOB, RAW

CHAR

CHAR

DATE

DATE

DATETIME

DATE

DECIMAL

FLOAT (24)

DOUBLE

FLOAT (24)

DOUBLE PRECISION

FLOAT (24)

ENUM

VARCHAR2

FLOAT

FLOAT

INT

NUMBER(10, 0)

INTEGER

NUMBER(10, 0)

LONGBLOB

BLOB, RAW

LONGTEXT

CLOB, RAW

MEDIUMBLOB

BLOB, RAW

MEDIUMINT

NUMBER(7, 0)

MEDIUMTEXT

CLOB, RAW

NUMERIC

NUMBER

REAL

FLOAT (24)

SET

VARCHAR2

SMALLINT

NUMBER(5, 0)

TEXT

VARCHAR2, CLOB

TIME

DATE

TIMESTAMP

DATE

TINYBLOB

RAW

TINYINT

NUMBER(3, 0)

TINYTEXT

VARCHAR2

VARCHAR

VARCHAR2, CLOB

YEAR

NUMBER


Note:

The ENUM and SET data types have no direct mapping in Oracle. SQL Developer maps ENUM columns in MySQL to VARCHAR2 columns in Oracle. It then adds a constraint and a trigger to those columns to ensure that only values that were allowed by the ENUM data type are allowed in the column it was mapped to in Oracle.

2.3.3 Comparing Data Types

This section lists the difference between MySQL and Oracle data types. For some MySQL data types there is more than one alternative Oracle data type. The tables include information about the following:

2.3.3.1 Numeric Types

When mapping MySQL data types to numeric data types in Oracle, the following conditions apply:

  • If there is no precision or scale defined for the destination Oracle data type, precision and scale are taken from the MySQL source data type.

  • If there is a precision or scale defined for the destination data type, these values are compared to the equivalent values of the source data type and the maximum value is selected.

The following table compares the numeric types of MySQL to Oracle:

MySQLSizeOracle
BIGINT8 BytesNUMBER (19,0)
BITapproximately (M+7)/8 BytesRAW
DECIMAL(M,D)M+2 bytes if D > 0, M+1 bytes if D = 0 (D+2, if M < D)FLOAT(24), BINARY_FLOAT
DOUBLE8 BytesFLOAT(24), BINARY_FLOAT, BINARY_DOUBLE
DOUBLE PRECION8 BytesFLOAT(24), BINARY_DOUBLE
FLOAT(25<=X <=53)8 BytesFLOAT(24), BINARY_FLOAT
FLOAT(X<=24)4 BytesFLOAT, BINARY_FLOAT
INT4 BytesNUMBER (10,0)
INTEGER4 BytesNUMBER (10,0)
MEDIUMINT3 BytesNUMBER (7,0)
NUMERICM+2 bytes if D > 0, M+1 bytes if D = 0 (D+2, if M < D)NUMBER
REAL8 BytesFLOAT(24), BINARY_FLOAT
SMALLINT2 BytesNUMBER(5,0)
TINYINT1 ByteNUMBER(3,0)

2.3.3.2 Date and Time Types

The following table compares the date and time types of MySQL to Oracle:

MySQLSizeOracle
DATE3 BytesDATE
DATETIME8 BytesDATE
TIMESTAMP4 BytesDATE
TIME3 BytesDATE
YEAR1 ByteNUMBER

2.3.3.3 String Types

When mapping MySQL data types to character data types in Oracle, the following conditions apply:

  • If there is no length defined for the destination data type, the length is taken from the source data type.

  • If there is a length defined for the destination data type, the maximum value of the two lengths is taken.

The following table compares the string types of MySQL to Oracle:

Note:

Reference to M indicates the maximum display size. The maximum legal display size is 255. A reference to L applies to a floating point types and indicates the number of digits following the decimal point.
MySQLSizeOracle
BLOBL + 2 Bytes whereas L<2^16RAW, BLOB
CHAR(m)M Bytes, 0<=M<=255CHAR
ENUM (VALUE1, VALUE2, ...)1 or 2 Bytes depending on the number of enum. values (65535 values max) 
LONGBLOBL + 4 Bytes whereas L < 2 ^ 32RAW, BLOB
LONGTEXTL + 4 Bytes whereas L < 2 ^ 32RAW, CLOB
MEDIUMBLOBL + 3 Bytes whereas L < 2^ 24RAW, BLOB
MEDIUMTEXTL + 3 Bytes whereas L < 2^ 24RAW, CLOB
SET (VALUE1, VALUE2, ...)1, 2, 3, 4 or 8 Bytes depending on the number of set members (64 members maximum) 
TEXTL + 2 Bytes whereas L<2^16VARCHAR2, CLOB
TINYBLOBL + 1 Bytes whereas L<2 ^8RAW, BLOB
TINYTEXTL + 1 Bytes whereas L<2 ^8VARCHAR2
VARCHAR(m)L+1 Bytes whereas L<=M and0<=M<=255 before MySQL 5.0.3 (0 <= M <= 65535 in MySQL 5.0.3 and later; effective maximum length is 65,532 bytes)VARCHAR2, CLOB

2.4 Data Storage Concepts

This section provide a description of the conceptual differences and similarities in data storage for MySQL and Oracle databases.

Data storage is an aspect of MySQL that sets it apart for nearly every database, including Oracle. In MySQL, databases correspond to directories within the data directory of the server. Tables within a database correspond to one or more files within the database directory, depending on the storage engine used for the tables.

A database can contain a mix of tables of different storage engines. A storage engine is responsible for the storage and retrieval of the data for a table.

MySQL offers a variety of storage engines (formerly called table types) to meet the different requirements of the user's environment. Table 2-5 shows the storage engines supported by MySQL.

Table 2-5 Storage Engines Supported by MySQL

Storage EngineDescription

MyISAM

The default non-transactional storage engine that provides full-text indexing and is highly portable

MERGE

A non-transactional storage engine that allows a collection of MyISAM tables with identical column and index information to be used as one

MEMORY (HEAP)

A non-transactional storage engine that stores data in memory

BDB (Berkeley DB)

The first transactional-safe storage engine

InnoDB

A transactional-safe storage engine designed for maximum performance when processing large volume of data and that provides row-level locking

FEDERATED

A storage engine that accesses data in tables of remote databases rather than in local tables

ARCHIVE

A storage engine that can store large amount of data without indexes in very small footprint

CSV

A storage engine that stores data in text file using comma-separated-values format

BLACKHOLE

A storage engine that acts as a "black hole" that accepts data but throws it away and does not store it

EXAMPLE

A "stub" engine that does nothing. Its purpose is to serve as an example that illustrates how to begin writing new engines.

ISAM

The original MySQL storage engine that has been deprecated in favor of the MyISAM storage engine as of version 5.0


Each storage engine has its benefits and drawbacks. Some of features that differentiate the storage engines are transaction, locking, concurrency and portability. The following table summarizes the features for four of the commonly used storage engines.

Table 2-6 Feature Comparison for Common Storage Engines

FeatureMyISAMHeapBDBInnoDB

Transactional

No

No

Yes

Yes

Lock granularity

Table

Table

Page

Row

Storage

A data file (.MYD) and an index file (.MYI) for each table

In-memory

A single data and index file (.db) for each table

A set of data files for all the tables

Portable

Yes

N/A

No

Yes


An Oracle database consists of one or more tablespaces. Tablespaces provide logical storage space that link a database to the physical disks that hold the data. A tablespace is created from one or more data files. Data files are files in the file system or an area of disk space specified by a raw device. A tablespace can be enlarged by adding more data files.

An Oracle database consists of a least a SYSTEM tablespace, where the Oracle tables are stored. It can also consist of user defined tablespaces. A tablespace is the logical storage location for database objects. For example, you can specify where a particular table or index gets created in the tablespace.

Posted by redkite
, |

1. SQL> Shutdown immediate

2. $ cp /oracle/maxprd1/system01.dbf to /oracle/maxprd1/maxlive/system01.dbf

3. SQL> startup mount

4. SQL> alter database rename file '/oracle/maxprd1/system01.dbf' to '/oracle/maxprd1/maxlive/system01.dbf';

5. SQL> alter database open.

6. $ rm /oracle/maxprd1/system01.dbf

'01.오라클 > 002.DB 마이그레이션' 카테고리의 다른 글

[오라클]MySQL Vs. Oracle  (0) 2013.04.19
[오라클]Characterset 변경  (0) 2013.02.20
[오라클]Full export / import  (0) 2013.02.20
[오라클]Undo Tablespace 변경  (0) 2012.12.19
[오라클]Voting Disk 이관  (0) 2012.12.19
Posted by redkite
, |

한글을 지원하는 캐릭터셋 
1.KO16KSC5601 
2.KO16MSWIN949 
3.UTF8 
4.AL32UTF8 

A. 작업 전 만약을 위해 DB전체를 백업 받아둔다. character set 을 잘못 변경하면 DB를 open 할수 없을 수 있다. 
B. 오라클 캐릭터셋 확인쿼리 
  SELECT parameter,value FROM nls_database_parameters WHERE parameter like '%CHAR%'; 
-------------------------------------- 
C. 아래는 OTN에서 발췌한 내용 
8i(AMERICAN_AMERICA.US7ASCII)는 version 8.1.6 이상이라고 가정하겠습니다. 아래의 내용 중의 일부분은 Oracle database release 8.1.6 이상에서만 적용될 수 있습니다. 
기본 작업 절차 
-------------- 
(1) CLOB data에 대한 unloading/exporting. 
(2) 8i(AMERICAN_AMERICA.US7ASCII)에서 "ALTER DATABASE CHARACTER SET" command set을 통한 8i(AMERICAN_AMERICA.KO16KSC5601)로의 변환. 
(3) 8i(AMERICAN_AMERICA.KO16KSC5601)에서 NLS_LANG 환경변수 변경(KOREAN_KOREA.KO16KSC5601)을 통한 8i(KOREAN_KOREA.KO16KSC5601)로의 변환. 
(4) 8i(KOREAN_KOREA.KO16KSC5601)에서 exporting 후 9i(KOREAN_KOREA.KO16KSC5601)에서 importing. 
(5) CLOB data에 대한 loading/importing. 
과정(2)의 세부 절차 
------------------ 
$ sqlplus /nolog 
SQL> conn sys/pw as sysdba 
SQL> shutdown immediate 
SQL> startup mount 
SQL> alter system enable restricted session; 
SQL> alter system set JOB_QUEUE_PROCESSES=0; 
SQL> alter system set AQ_TM_PROCESSES=0; 
SQL> alter database open; 
SQL> alter database character set KO16KSC5601; 
SQL> alter database national character set KO16KSC5601; 
SQL> shutdown immediate 
SQL> startup open 
  

ERROR at line 1: 
ORA-12716: Cannot ALTER DATABASE CHARACTER SET when CLOB data exists 
## 에러가 발생할 경우 아래 스크립트로 실행한다. 
SQL> alter database  character set internal_use ko16ksc5601; 
  
CF) DB내의 CLOB 찾기 
CLOB 또는 NCHAR Datatype의 컬럼들을 export 받고 
CLOB, NCHAR이 포함된 Table을 Drop하고 
Alter database character set ... 하고 
다시 Import하라고 되어 있는데 별 효용없는것 같음. 
sys, system으로 접속하여 
SELECT * 
FROM dba_lobs 
Partitioning했다면 DBA_PART_LOBS까지 참조 

'01.오라클 > 002.DB 마이그레이션' 카테고리의 다른 글

[오라클]MySQL Vs. Oracle  (0) 2013.04.19
[오라클]system tablespace rename  (0) 2013.02.23
[오라클]Full export / import  (0) 2013.02.20
[오라클]Undo Tablespace 변경  (0) 2012.12.19
[오라클]Voting Disk 이관  (0) 2012.12.19
Posted by redkite
, |

## export

형식 :  EXP KEYWORD=값 또는 KEYWORD=(값1,값2,...,값N)

예    :  EXP SCOTT/TIGER GRANTS=Y TABLES=(EMP,DEPT,MGR)
           또는 T1이 분할된 테이블인 경우 TABLES=(T1:P1,T1:P2)

 

예 ) exp scott/tiger file=emp.dmp log=emp.log tables=emp direct=y
예 ) exp system/oracle file=full.dmp full=y indexes=n triggers=n
예 ) exp system/oracle file=scott.dmp owner=scott rows=n

 

option

수많은 exp 옵션들... 다 외울순 없다..

exp help=y

하게 되면 친절히 설명해주니 기억이 나지 않을시 참고 하도록 하자


scott/tiger                           : db 유저/password
full                                       : 해당 db 전체 데이터 추출 여부(기본값 N)
buffer                                   : 작업 단위의 크기 설정
owner                                  :  db 유저별 오브젝트 추출 설정
file                                       : 추출한 데이터를 저장할 파일 이름 설정
tables                                  : 데이터를 추출할 대상 테이블 설정
compress                            :  익스텐트 통합 여부를 지정(기본값 Y)
grants                                  : 오브젝트 권한 설정에 대한 정보 추출 여부(기본값 Y)
indexes                                : 인덱스 스크립트 추출 여부(기본값 Y)
direct                                   : 직접 경로로 export 수행 여부(기본값 N)
triggers                                  : 트리거 정보 추출 여부(기본값 Y)
log                                       : 로그를 저장할 파일 지정
rows                                     : 테이블의 데이터 추출 여부(기본값 Y)
consistent                             : 대상 테이블의 읽기 일관성 지정(기본값 N)
constraints                            : 제약 조건의 추출 여부(기본값 Y)
parfile                                 :  파라메터 파일을 export시 적용
INCTYPE                               : 증분 엑스포트 유형
RECORD                               : 증분 엑스포트 추적(기본값 Y)

OBJECT_CONSISTENT            : 객체 엑스포트 동안 읽기 전용으로 설정된 트랜잭션(N)
FEEDBACK                            : 매 x행마다 진행 상황 표시(0)
FILESIZE                             : 각 덤프 파일의 최대 크기
FLASHBACK_SCN                   : 세션 스냅샷을 되돌리는 설정에 사용된 SCN
FLASHBACK_TIME                  : 지정된 시간에 가장 가까운 SCN을 가져오는 데 사용된 시간
QUERY                                 : 테이블의 부분 집합을 엑스포트하는 데 사용된 select 절
RESUMABLE                          : 공간 관련 오류가 발생하면 일시 중지됨(N)
RESUMABLE_NAME                : 재개 가능한 명령문을 식별하는 데 사용된 텍스트 문자열
RESUMABLE_TIMEOUT            : RESUMABLE 대기 시간
TTS_FULL_CHECK                   : TTS에 대한 전체 또는 부분 종속성 검사 수행
TABLESPACES                     : 엑스포트할 테이블스페이스 목록
TRANSPORT_TABLESPACE : 이동 가능한 테이블스페이스 메타 데이터 엑스포트(N)
TEMPLATE                             : iAS 모드 엑스포트를 호출하는 템플리트 이름

 

** compress 옵션을 Y로 설정 하여 사용하면 여러개의 익스텐트가 하나의 큰 익스텐트로 통합된다
   실제 운영에서는 익스텐트를 통합하는것은 좋지 않으므로 반드시 compress 옵션을 N로 설정 한다.
** direct 옵션을 사용하면 SGA를 사용하지 않고 export/import 하게 되며 
   추출 및 적재 작업시 보다 빠른 속도를 보장 받는다.
** comsistent 옵션을 Y로 설정하면 export를 수행한 시점의 데이터를 추출한다.
   export 중 변경된 데이터는 언두 데이터를 이용해서 이전 값을 추출한다.
   따라서 'snap shot too old' 에러가 발생하기 쉽다.


## export 작업시 주의 사항

** full, ower 및 tables 옵션은 동시 사용 불가
** direct=Y인 경우 consistent=y로 설정 불가
** full=Y로 expor를 수행하기 위해서는 exp_full_database 권한 필요

 

----- 추출 파일의 크기를 확인하는 SQL

SQL> select sum(bytes)/1024/1024
     from dba_segments
     where segment_name='TEST';

 

export 작업을 수행 하면 실제 테이블의 크기보다 작게 생성된다.
위 SQL을 수행하여 나온 크기만큼 디스크의 크기를 확보하면 export 작업을 수행하는데 충분하다.
또한 추출 파일에는 해당 테이블의 인덱스를 생성할 수 있는 정의만 저장하므로 별도의 디스크공간은 필요하지 않다.
하지만 import 시에는 실제 인덱스를 생성하므로 인덱스 테이블스페이스에 여유 공간을 확보해야한다.


## import

-- import 순서 : 테이블 생성 > 데이터 적재 > B*트리 인덱스 생성 > 제약조건 > 트리거 및 비트맵 인덱스 생성

 

예 ) imp scott/tiger file=emp.dmp log=emp.log tables=emp
예 ) system/manager file=full.dmp log=full.log full=y
예 ) system/manager file=scott.dmp fromuser=scott touser=mike

 

option

scott/tiger                         : db 유저 / password
full                                     : 전체 db에 대해 import 여부(기본값 N)
buffer                                 : 작업 단위의 크기 지정
fromuser                       : export한 테이블의 소유자 지정
touser                                : import되는 테이블의 소유자 지정
tables                                : import 대상 테이블 지정
ignore                                : import 대상 테이블이 존재할 경우 에러 발생 여부(기본값 N)
grants                                 : 권한 적재 여부 지정 (기본값 Y)
indexes                             : index 생성 여부(기본값 Y)
commit                               : import 수행중 커밋 수행여부, 
                                           Y로 지정할 경우 buffer 옵션 단위로 커밋 수행(기본값 N)
rows                                   : 테이블의 데이터 적재 여부(기본값 Y)
log                                     : 로그를 저장할 파일 지정
constrainsts                      : 제약 조건 적재 여부(기본값 Y)
parfile                                : 파라메터 파일을 지정하여 import 작업시 적용

SHOW                                 : 파일 목차만 목록 (기본값 N)
RECORDLENGTH IO               : 레코드의 길이
INCTYPE                              : 증분 임포트 유형
DESTROY                             : 테이블스페이스 데이터 파일 겹쳐쓰기(기본값 N)
INDEXFILE                          : 지정된 파일에 테이블/인덱스 정보 쓰기
SKIP_UNUSABLE_INDEXES     : 사용되지 않은 인덱스들의 유지를 건너뜁니다 (기본값 N)
FEEDBACK                           : 매 x행마다 진행 상황 표시(기본값 0)
TOID_NOVALIDATE                : 지정된 유형 ID 검증 건너뛰기
FILESIZE                            : 각 덤프 파일의 최대 크기
STATISTICS                          : 미리 계산된 통계 임포트(항상)
RESUMABLE                         : 공간 관련 오류가 발생하면 일시 중지됨(기본값 N)
RESUMABLE_NAME               : 재개 가능한 명령문을 식별하는 데 사용되는 텍스트 문자열
RESUMABLE_TIMEOUT          : RESUMABLE 대기 시간
COMPILE                              : 프로시저, 패키지 및 함수 컴파일(기본값 Y)
STREAMS_CONFIGURATION   : 일반 스트림 메타 데이터 임포트(기본값 Y)
STREAMS_INSTANTIATION      : 스트림 인스턴스화 메타 데이터 임포트(기본값 N)

 

아래의 키워드만이 이동가능한 테이블스페이스에 적용할 수 있다.

TRANSPORT_TABLESPACE  : 이동가능한 테이블스페이스 메타데이터을 임포트합니다 (기본값 N)
TABLESPACES                     : 데이터베이스안에 테이블스페이스가 이동되었습니다
DATAFILES                            : 데이터베이스안에 데이터 파일들이 이동되었습니다
TTS_OWNERS                          : 이동가능한 테이블스페이스 설정에 데이터를 소우하고 있는 사용자

 

## import 작업시 주의 사항

** full 옵션과 tables 옵션은 동시 사용 불가
** full=y 및 touser 옵션을 사용하기 위해서는 imp_fyll_database 권한 필요
** 적은 양의 데이터 import 경우를 제외하곤 commit 옵션을 Y로 설정 권장.
** export 시와 동일한 tablespace가 존재하지 않을 경우 유저 default tablespace로 import 된다
   system 유저로 import 하게 되면 system tablespace에 일반 유저 세그먼트가 생성 될수 있으므로
   반드시 export시 tablespace와 동일한 이름의 tablespace를 생성한 후 작업을 수행해야한다.

 

------------------------- exp/imp 실습 --------------------------

실습 준비 사항

SQL> create tablespace test datafile 'D:\ORACLE\PRODUCT\10.2.0\ORADATA\ORCL\TEST1.DBF' size 1m;

SQL> alter tablespace test add datafile 'D:\ORACLE\PRODUCT\10.2.0\ORADATA\ORCL\TEST2.DBF' size 1m;

SQL> alter tablespace test add datafile 'D:\ORACLE\PRODUCT\10.2.0\ORADATA\ORCL\TEST3.DBF' size 1m;

SQL> create user orcl identified by orcl
  2  default tablespace test;

SQL> grant connect, resource, select any table to orcl;

SQL> grant exp_full_database, imp_full_database to orcl;            // exp, imp database 사용시

SQL> create table orcl.test as select * from scott.emp;


------------------------- exp/imp database --------------------------

## exp 백업의 이름을 잘 정해야 한다. 해당 백업 파일을 언제 누가 보든 쉽게 이해할수있도록 룰을 잘 정해야한다.
## exp의 경우 datapump와 다르게 디렉토리 지정이 없다.
## exp 할 대상 경로로 이동해 실행하거나, 
## file=[ 경로명 ]\test.dmp , log=[ 경로명 ]\test.log 와 같이 직접 지정해야한다.


D:\test>exp orcl/orcl full=y log=test.log file=test.dmp

엑스포트가 경고 없이 정상적으로 종료되었습니다.

D:\test>dir

2009-04-15  오후 01:12        82,259,968 test.dmp
2009-04-15  오후 01:12            61,816 test.log

D:\test>imp orcl/orcl full=y file=testfull.dmp
.
.
IMP-00015: 객체가 이미 존재하므로 다음 명령이 실패했습니다
 "CREATE UNDO TABLESPACE "UNDOTBS1" BLOCKSIZE 8192 DATAFILE  'D:\ORACLE\PRODU"
 "CT\10.2.0\ORADATA\ORCL\UNDOTBS01.DBF' SIZE 62914560       AUTOEXTEND ON NEX"
 "T 5242880  MAXSIZE 32767M EXTENT MANAGEMENT LOCAL "
.
.

########## 완료시 경고성 완료가 될수 있다. 이유? 당연히 DB가 멀쩡히 있기 때문이다.
########## 작업중 err를 발생할 수도 있다.. 걱정마라 system 관련 parameter 또는 동적 뷰다.
########## system 관련 데이터까지 모두 날릴순 없지 않은가..
########## 그럼 어떨때 export/import database를 쓸까??
########## 마이그레이션 작업할때 쓴다!!!

 

D:\test>imp orcl/orcl full=y file=testfull.dmp ignore=y

엑스포트 파일은 직접 경로를 거쳐 EXPORT:V10.02.01 에 의해 생성되었습니다
KO16MSWIN949 문자집합과 AL16UTF16 NCHAR 문자 집합에 임포트가 완성되었습니다
. SYSTEM 객체를 SYSTEM(으)로 임포트하는 중입니다
. OLAPSYS 객체를 OLAPSYS(으)로 임포트하는 중입니다
.
.


-------------------------- exp/imp transport_tablespace --------------------------

같은 환경을 가진 두개 이상의 분산 DB 환경에서 어떤 DB가 가진 여러개의 데이터 파일을 다른 DB로 이동 시키는 기능.

 

------- 주의사항
## transport_tablespace를 사용하려면 해당 tablespace를 read only 시켜야 한다.
## tablespace내 하나의 특정 데이터 파일만 이동 할수 없다.
## 같은 환경을 가진 OS에서만 가능함.
## 오라클 8i 이상 사용 가능.
## DB_BLOCK_SIZE 파라메터의 값이 같아야 함.
## 같은 언어타입을 사용해야함.
## VARRAY 타입과 중첩 테이블 컬럼이 있는 테이블은 사용할수 없음.
## bit-map-index는 사용할수 없음.

## LOB 타입을 가진 테이블 또는 분할 테이블은 사용할수 있음.


SQL> conn orcl/orcl
연결되었습니다.

 

SQL> select count(*) from test;

  COUNT(*)
----------
        14

 

SQL> conn / as sysdba
연결되었습니다.


SQL> select tablespace_name, status from dba_tablespaces;

TABLESPACE_NAME                STATUS
------------------------------ ---------
SYSTEM                                  ONLINE
UNDOTBS1                               ONLINE
SYSAUX                                  ONLINE
TEMP                                      ONLINE
USERS                                     ONLINE
EXAMPLE                                ONLINE
TEST                                       ONLINE

7 개의 행이 선택되었습니다.

 

SQL> alter tablespace test read only;         // export transport tablespace 하려면 
테이블스페이스가 변경되었습니다.              // tablespace를 read only로 변경해야한다

SQL> exit

-------------------- export transport tablespace 시작
D:\test>exp '/ as sysdba' file=aaa.dmp transport_tablespace=y tablespaces=test
.
.
엑스포트가 경고 없이 정상적으로 종료되었습니다.

 

D:\test>sqlplus / as sysdba

 

SQL> drop tablespace test including contents;

테이블스페이스가 삭제되었습니다.

 

SQL> select * from orcl.test;                   // tablespace가 삭제 되어서 table을 찾을수 없다.
select * from orcl.test
              *
1행에 오류:
ORA-00942: 테이블 또는 뷰가 존재하지 않습니다

 

SQL> exit

------------------------- aaa.dmp 파일을 이용한 tablespace import
D:\test>imp '/ as sysdba' file=aaa.dmp transport_tablespace=y tablespaces=test datafiles=D:\ORACLE\P
임포트가 경고 없이 정상적으로 종료되었습니다.

 

D:\test>sqlplus orcl/orcl

 

SQL> select count(*) from test;

  COUNT(*)
----------
        14

 

SQL> select tablespace_name, status from dba_tablespaces;          

TABLESPACE_NAME                STATUS
------------------------------ ---------
SYSTEM                         ONLINE
UNDOTBS1                       ONLINE
SYSAUX                         ONLINE
TEMP                           ONLINE
USERS                          ONLINE
EXAMPLE                        ONLINE
TEST                           READ ONLY

7 개의 행이 선택되었습니다.

 

SQL> alter tablespace test read write;               // import 완료 했으므로 다시 online으로 변경

테이블스페이스가 변경되었습니다.


------------------------------------- exp/imp table--------------------------------------

예 ) exp orcl/orcl file=test.dmp log=test.log tables=test
예 ) exp orcl/orcl file=test.dmp log=test.log tables=scott.emp
예 ) exp orcl/orcl file=test.dmp log=test.log tables=(scott.emp, hr.employees, scott.dept)


SQL> select count(*) from test;

  COUNT(*)
----------
        14

 

D:\test>exp orcl/orcl file=test.dmp log=test.log tables=ss
.
.
엑스포트가 경고 없이 정상적으로 종료되었습니다.


####### case 1) table을 drop 한 경우 #######

SQL> drop table test;

 

SQL> select count(*) from test;
select count(*) from test
                     *
1행에 오류:
ORA-00942: 테이블 또는 뷰가 존재하지 않습니다

 

D:\test>imp orcl/orcl file=table.dmp tables=test
임포트가 경고 없이 정상적으로 종료되었습니다.

 

SQL> select count(*) from test;

  COUNT(*)
----------
        14


####### case 2) table을 delete 한 경우 #######

SQL> delete test;

14 행이 삭제되었습니다.

 

SQL> select * from test;

선택된 레코드가 없습니다.

 

SQL> commit;

커밋이 완료되었습니다.

 

D:\test>imp orcl/orcl file=table.dmp tables=test
.
.
 "CREATE TABLE "TEST" ("EMPNO" NUMBER(4, 0), "ENAME" VARCHAR2(10), "JOB" VARC"
 "HAR2(9), "MGR" NUMBER(4, 0), "HIREDATE" DATE, "SAL" NUMBER(7, 2), "COMM" NU"
 "MBER(7, 2), "DEPTNO" NUMBER(2, 0))  PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRA"
 "NS 255 STORAGE(INITIAL 65536 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFA"
 "ULT)                   LOGGING NOCOMPRESS"
경고와 함께 임포트가 정상 종료되었습니다.

 

// imp table을 할때 create table 구문이 들어가 있다.
// 즉, table의 row는 없더라도 같은 이름의 table이 있다면 import 되지 않는다.
// 이러한 경우 ignore=y 옵션을 사용한다.

D:\test>imp orcl/orcl file=table.dmp tables=test ignore=y

임포트가 경고 없이 정상적으로 종료되었습니다.

 

SQL> select count(*) from test;

  COUNT(*)
----------
        14


####### case 2) data가 들어있는 table에 ignore 옵션을 사용할 경우 #######
SQL> select count(*) from test;

  COUNT(*)
----------
        14

 

D:\test>imp orcl/orcl file=table.dmp tables=test ignore=y

임포트가 경고 없이 정상적으로 종료되었습니다.

 

SQL> select count(*) from test;

  COUNT(*)
----------
        28

 

// row수가 14개 더 늘어난걸 볼수있다.
// ignore 옵션은 해당 테이블에 중복 데이터가 있으면 해당 데이터를 덮어 쓰는게 아니다.

 

----------------------------------- exp/imp owner ---------------------------------------

D:\test>exp '/ as sysdba' file=user.dmp log=user.log owner=orcl

엑스포트가 경고 없이 정상적으로 종료되었습니다.

 

SQL> drop user orcl cascade;                    // 해당 유저와 유저의 데이터까지 모두 삭제.

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

 

SQL> create user orcl identified by orcl
  2  default tablespace test;

사용자가 생성되었습니다.

 

SQL> grant connect, resource to orcl;

권한이 부여되었습니다.

 

D:\test>imp '/ as sysdba' file=user.dmp fromuser=orcl touser=orcl

경고와 함께 임포트가 정상 종료되었습니다.

 

SQL> select count(*) from test;

  COUNT(*)
----------
        14

 

------------------------------ exp/imp query ------------------------------------

## export시 쿼리 문을 사용하여 해당 table내 원하는 데이터만 추출할수 있다.
   - 테이블 레벨의 export 명령어에서만 가능하다.
   - Direct 옵션과 함께 사용될 수 없다.
   - Nested 테이블을 갖는 테이블에는 적용할 수 없다.
   - Partition 테이블에 대한 export에도 적용가능하다.
   - Import 명령에는 적용되지 않는다.

 

D:\test>exp orcl/orcl file=dump.emp log=dump.log tables=orcl.test query='where empno=7788'

엑스포트가 경고 없이 정상적으로 종료되었습니다.

 

------------------------------------ 참고 사항 ---------------------------------------------
## UNIX reserved characters( ", ', ,< .. 등)를 사용하는 경우에는 escape ('\') 을 반드시 사용해야 한다.

 

----- win
예 ) exp orcl/orcl file=dump.emp log=dump.log tables=orcl.test query=\"where ename like 'SCOT%'\"
----- UNIX
예 ) exp orcl/orcl file=dump.emp log=dump.log tables=orcl.test query=\"where ename like \'SCOT%\'\"

 

## command line에서 query 내에 '," 을사용하지 않는 다면 '나 " 으로 query option을 사용할수 있다
   query=\'where deptno = 20\'
   query=\"where deptno = 20\"
   query=\'where deptno \< 2\' 
   (이 경우  single 이나  double quotes 을 둘다 사용할수 있다.)

 

## command line에서 export option을 사용할때는 반드시 escape가 있어야 하나 
   parfile을 사용할때는 eacape이 불필요하다.
 
  
parfile을 사용하는 경우에는 다음과 같이 단순하게  사용이 가능하다.
query='where deptno = 20'
query="where deptno = 20"
query='where deptno < 20'


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


########### case 1) ########### 
SQL> drop table test;

 

D:\test>imp orcl/orcl file=dump.emp tables=test

임포트가 경고 없이 정상적으로 종료되었습니다.

 

SQL> select count(*) from test;

  COUNT(*)
----------
         1


########### case 2) ########### 
SQL> delete from test where empno=7788;

 

SQL> commit;

 

SQL> select count(*) from test;

  COUNT(*)
----------
        13

 

D:\test>imp orcl/orcl file=table.dmp tables=test ignore=y

임포트가 경고 없이 정상적으로 종료되었습니다.

 

SQL> select count(*) from test;

  COUNT(*)
----------
        14


// 실제로 imp된 7788사원은 해당 테이블의 가장 마지막 로우에 import 된다.


## 그렇다면 table 단위로 emp 하고 query로 뽑아서 import 할수 있을까?
   -> 정답은 안된다. 궁금하면 해보시라.
   LRM-00101: 알 수 없는 'query' 매개변수 이름. 이런 메세지가 기다리고 있을것이다.

 

---------------------------------- exp/imp parfile 방식 -----------------------------------

## parfile 안에 해당 exp/imp 설정을 작성한후 parfile을 이용해서 exp/imp를 할수있다.

 

########### exp case 1
file=full.dmp
log=full.log
full=y
direct=y
.
.

########### exp case 2
file=emp.dmp
log=emp.log
tables=scott.emp
direct=y
.
.

########### exp case 3
file=scott.dmp
log=scott.log
owner=scott
direct=y
.
.
########### exp case 4
file=query.dmp
log=query.log
tables=scott.emp
query="where ename like 'SCOT%'"
direct=y
.
.

---------------------------
// 윈도우 이기 때문에 노트 패드로 pa.par 파일을 작성 한뒤 실습 내용임


D:\test>more pa.par
file=table.dmp
log=table.log
tables=orcl.test
direct=y

 

D:\test>exp test/test parfile=pa.par

엑스포트가 경고 없이 정상적으로 종료되었습니다.

 

D:\test>more impa.par
file=table.dmp
tables=test

 

D:\test>imp orcl/orcl parfile=impa.par

임포트가 경고 없이 정상적으로 종료되었습니다.

 

SQL> select count(*) from test;

  COUNT(*)
----------
        14

 

--------------------------------------- DIALOG 방식 -----------------------------------

D:\test>exp

Export: Release 10.2.0.1.0 - Production on 수 4월 15 15:54:52 2009

Copyright (c) 1982, 2005, Oracle.  All rights reserved.


사용자명: test
암호:

다음에 접속됨: Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - Production
With the Partitioning, OLAP and Data Mining options
배열 인출 버퍼 크기 입력: 4096 > 409

엑스포트 파일: EXPDAT.DMP > 111

(1)E(전체 데이터베이스), (2)U(사용자), 또는 (3)T(테이블): (2)U > 1

권한부여 엑스포트 (yes/no): yes > yes

테이블 데이터 엑스포트 (yes/no): yes > yes

확장 영역 압축 (yes/no): yes > yes

KO16MSWIN949 문자 설정과 AL16UTF16 NCHAR 문자 설정에서 엑스포트가 종료되었습니다

전체 데이터베이스를 엑스포트하려고 합니다 ...
테이블 정의 엑스포트 중
프로파일 엑스포트 중
사용자 정의 엑스포트 중
.
.
.

Posted by redkite
, |

오라클9i 이상 filesystem UNDO TABLESPACE 변경
- All undo tablespaces are created permanent, read/write, and in logging mode.

 

1. 기존 UNDO TABLESPACE를 DROP 후 CREATE

    SQL> connect / as sysdba

    SQL> CREATE  UNDO TABLESPACE UNDOIMSI

                           DATAFILE '/oradata/undoimsi.dbf' SIZE 10M;
    SQL> ALTER SYSTEM SET UNDO_TABLESPACE=UNDOIMSI;

    SQL> DROP TABLESPACE UNDOTBS1 INCLUDING CONTENTS AND DATAFILES;
    SQL> CREATE  UNDO TABLESPACE "UNDOTBS1"
                           DATAFILE '/oradata/undotbs01.dbf' SIZE 500M
                           EXTENT MANAGEMENT LOCAL;
   SQL> ALTER SYSTEM SET UNDO_TABLESPACE=UNDOTBS1;

   SQL> DROP TABLESPACE UNDOIMSI INCLUDING CONTENTS AND DATAFILES;

 

2. UNDO datafile Resize
    SQL> connect / as sysdba

    SQL> alter database datafile '/oradata/UNDOTBS01.dbf' resize 4000M;

 

Posted by redkite
, |

사용하던 스토리지 교체로 ocr 과 voting disk 를 새로운 스토리지로 이관하는 내용입니다.

작업 하기 전에 준비되어야 하는 것은 기존 스토리지와 새로운 스토리지 모두 서버에서 바라 볼수 있어야 합니다.

이 작업은 하드웨어 엔지니어분께 얘기하면 알아서 해주실 겁니다.

기존 스토리지의 볼륨 그룹은 rac1 이고 새로운 스토리지의 볼륨 그룹은 rac2 입니다.

ocr은 replace 하고, voting 은 add 하고 delete 합니다.

작업 하시기 전 불의의 사고(?) 에 대비해 ocr 과 voting disk 모두 백업 하시고요,

저는 이런식으로 했는데 상황에 따라 다른 여러가지 방법이 존재할 수 있을 겁니다.

note 428681.1 를 참고 했으며, 꼭 읽어 본 후 작업 하세요.

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

모든 작업은 root 계정으로 한다.

OCR 은 crs 가 start 상태에서 작업하며, voting disk 는 crs 가 down 상태에서 한다.

1. OCR 현재 상태 확인

[db1:/oramedia/patch/6455161] su - root
Password:
Sun Microsystems Inc. SunOS 5.10 Generic January 2005
cdSourcing //.profile-EIS.....
root@db1 # cd $ORA_CRS_HOME
root@db1 # cd bin
root@db1 # ocrcheck
Status of Oracle Cluster Registry is as follows :
Version : 2
Total space (kbytes) : 524044
Used space (kbytes) : 4100
Available space (kbytes) : 519944
ID : 1967014107
Device/File Name : /dev/md/rac1/rdsk/d201
Device/File integrity check succeeded
Device/File Name : /dev/md/rac1/rdsk/d202
Device/File integrity check succeeded

Cluster registry integrity check succeeded

2. OCR 다른 스토리지로 이관
root@db1 # ocrconfig -replace ocr /dev/md/rac2/rdsk/d201
root@db1 # ocrcheck
Status of Oracle Cluster Registry is as follows :
Version : 2
Total space (kbytes) : 524044
Used space (kbytes) : 4100
Available space (kbytes) : 519944
ID : 1967014107
Device/File Name : /dev/md/rac2/rdsk/d201
Device/File integrity check succeeded
Device/File Name : /dev/md/rac1/rdsk/d202
Device/File integrity check succeeded

Cluster registry integrity check succeeded

root@db1 # ocrconfig -replace ocrmirror /dev/md/rac2/rdsk/d202
root@db1 # ocrcheck
Status of Oracle Cluster Registry is as follows :
Version : 2
Total space (kbytes) : 524044
Used space (kbytes) : 4100
Available space (kbytes) : 519944
ID : 1967014107
Device/File Name : /dev/md/rac2/rdsk/d201
Device/File integrity check succeeded
Device/File Name : /dev/md/rac2/rdsk/d202
Device/File integrity check succeeded

Cluster registry integrity check succeeded

3. voting disk 현재 상태 확인

root@db1 # crsctl query css votedisk
0. 0 /dev/md/rac1/rdsk/d203
1. 0 /dev/md/rac1/rdsk/d204
2. 0 /dev/md/rac1/rdsk/d205

located 3 votedisk(s).
root@db1 # crsctl add css votedisk /dev/md/rac2/rdsk/d203
Cluster is not in a ready state for online disk addition <= 온라인 상태라 등록이 안된다.

4. crs 중지 (모든 노드)

root@db1 # crsctl stop crs
Stopping resources. This could take several minutes.
Successfully stopped CRS resources.
Stopping CSSD.
Shutting down CSS daemon.
Shutdown request successfully issued.

5. voting disk 추가 및 기존 디스크 제거

root@db1 # crsctl add css votedisk /dev/md/rac2/rdsk/d203 -force
Now formatting voting disk: /dev/md/rac2/rdsk/d203
successful addition of votedisk /dev/md/rac2/rdsk/d203.
root@db1 # crsctl delete css votedisk /dev/md/rac1/rdsk/d203 -force
successful deletion of votedisk /dev/md/rac1/rdsk/d203.
root@db1 # crsctl add css votedisk /dev/md/rac2/rdsk/d204 -force
Now formatting voting disk: /dev/md/rac2/rdsk/d204
successful addition of votedisk /dev/md/rac2/rdsk/d204.
root@db1 # crsctl delete css votedisk /dev/md/rac1/rdsk/d204 -force
successful deletion of votedisk /dev/md/rac1/rdsk/d204.
root@db1 # crsctl add css votedisk /dev/md/rac2/rdsk/d205 -force
Now formatting voting disk: /dev/md/rac2/rdsk/d205
successful addition of votedisk /dev/md/rac2/rdsk/d205.
root@db1 # crsctl delete css votedisk /dev/md/rac1/rdsk/d205 -force
successful deletion of votedisk /dev/md/rac1/rdsk/d205.

6. crs 스타트 (모든 노드)
root@db1 # crsctl start crs
Attempting to start CRS stack
The CRS stack will be started shortly

7. voting disk 확인

root@db2 # crsctl query css votedisk
0. 0 /dev/md/rac2/rdsk/d204
1. 0 /dev/md/rac2/rdsk/d205
2. 0 /dev/md/rac2/rdsk/d203

located 3 votedisk(s).

8. ocr.loc 파일에서 ocr 경로 확인

root@db2 # cat /var/opt/oracle/ocr.loc
#Device/file /dev/md/rac1/rdsk/d202 getting replaced by device /dev/md/rac2/rdsk/d202
ocrconfig_loc=/dev/md/rac2/rdsk/d201
ocrmirrorconfig_loc=/dev/md/rac2/rdsk/d202

Posted by redkite
, |

오라클 9i 이상

- Locally Management Tablespace 권장

 

1. 기존 TEMP TABLESPACE를 DROP 후 CREATE

   SQL> connect / as sysdba

 

   SQL> CREATE TEMPORARY TABLESPACE IMSI TEMPFILE  '/oradata/imsi.dbf' size 10m;

   SQL> ALTER DATABASE DEFAULT TEMPORARY TABLESPACE IMSI;

   SQL> ALTER DATABASE TEMPFILE '/oradata/temp01.dbf' OFFLINE;
   SQL> DROP TABLESPACE TEMP INCLUDING CONTENTS AND DATAFILES;


   SQL> CREATE TEMPORARY TABLESPACE TEMP

                         TEMPFILE '/oradata/temp01.dbf' SIZE 1000M
                         EXTENT MANAGEMENT LOCAL UNIFORM SIZE 1M;
   SQL> ALTER DATABASE DEFAULT TEMPORARY TABLESPACE TEMP;

   SQL> ALTER DATABASE TEMPFILE '/oradata/imsi.dbf' OFFLINE;
   SQL> DROP TABLESPACE IMSI INCLUDING CONTENTS AND DATAFILES;

 

2. TEMPFILE RESIZE

   SQL> connect / as sysdba
   SQL> alter database tempfile '/oradata/temp01.dbf' resize 4000M; 

 

3. TEMPFILE RENAME

   SQL> shutdown immediate;
   SQL> !mv /data1/temp.dbf /data2/temp01.dbf (만약을 위해 cp를 사용할 것을 권장합니다.)
   SQL> startup mount
   SQL> alter database rename file '/data1/temp.dbf' to '/data2/temp01.dbf';
   SQL> alter database open;

8i에서는 tempfile이란 개념은 있었으나 default temporary tablespace라는
개념은 없었습니다. 그래서 유저에게 직접 default tablespace를 지정해주어야
했었습니다.
하지만.. 9i부터는 alter database default temporary tablespace new_temp;
명령을 하기만 하면 모든 유저의 default temporary tablespace가 default로
지정되어 있지 않으면 new_temp로 됩니다.
물론 이 경우에도 수동으로 temp를 지정할 수 있으니 실제로 유저가
temp공간을 어디에 사용하는지는..
select username, temporary_tablespace from dba_users; 를 통해서
확인해야 합니다.
scott유저는 default temporary tablespace로 지정되어서 그 쪽 temp를
사용하게 되니, 에러가 나지 않겠죠.

default temporary tablespace가 무엇으로 지정되어 있는지는,
select * from database_properties; 또는 select * from sys.props$; 로 조회하면
temporary tablespace라는 이름으로 어떤 값이 들어가 있는지 보입니다.

그리고 temp는 DB를 내렸다가 올리면 smon프로세스가 clear시켜줍니다.
temp는 아시다 싶이 당연히 sort를 해서 발생하는 것이구요. 그렇다면..
temp가 계속해서 full이 난다면.. temp를 사용하는 세션을 확인하고
temp를 사용하는 세션의 쿼리를 뽑아낸다면 쉽게 해결이 되겠죠.
아래는 제가 경험해서 처리한 것입니다.


저는 temporary tablespace가 full 났는데 도대체 쿼리를 못잡는 것이었습니다.
그래서 어떻게 했을까요? Secure CRT에 세션로그를 걸어두고 모니터링을 했죠.

vi stat.sh

interval=30 # Sleep interval in seconds
reps=1000000 # n times
j=1 # Loop variable

while [ $j -le ${reps} ]
do
echo " ----cycle ${j} / ${reps} --------"

sqlplus -s system/패스워드<<EOF
@sw.sql ${j}
exit
EOF
cat sess_${j}.dat >> sw.dat
rm sess_${j}.dat
sleep ${interval}
j=`expr ${j} + 1`
done
exit 0

vi sw.sql
set line 150
set concat "+"
col username format a10
col osuser format a10
col tablespace format a15
spool sess_&1.dat

SELECT b.tablespace,
b.segfile#,
b.segblk#,
b.blocks,
a.sid,
a.serial#,
c.spid,
a.username,
a.osuser,
a.status,
a.sql_hash_value
FROM v$session a,
v$sort_usage b,
v$process c
WHERE a.saddr = b.session_addr and a.paddr=c.addr
ORDER BY b.tablespace, b.segfile#, b.segblk#, b.blocks;
spool off

stats.sh 를 수행하고 PC킨 상태로 그냥두고 다음날 왔더니 아래처럼 temp를
계속 쓰는 넘이 나온거죠..
딱걸렸습니다.ㅎㅎ

TEMP 93 2550817 13824 92 58284 3193 PVB oracle ACTIVE 1126923165
----cycle 1792 / 1000000


TEMP 93 2550817 43008 92 58284 3193 PVB oracle ACTIVE 1126923165
----cycle 1793 / 1000000


TEMP 93 2550817 72192 92 58284 3193 PVB oracle ACTIVE 1126923165
----cycle 1794 / 1000000


TEMP 93 2550817 101376 92 58284 3193 PVB oracle ACTIVE 1126923165
----cycle 1795 / 1000000


TEMP 93 2550817 131072 92 58284 3193 PVB oracle ACTIVE 1126923165
----cycle 1796 / 1000000


TEMP 93 2416673 18944 123 5171 3197 PVB oracle ACTIVE 1126923165
TEMP 93 2550817 159744 92 58284 3193 PVB oracle ACTIVE 1126923165
----cycle 1797 / 1000000


TEMP 93 2416673 48128 123 5171 3197 PVB oracle ACTIVE 1126923165
TEMP

sql_hash_value값이 1126923165 이니 아래 쿼리에다가 넣으면 full 쿼리가 나오죠..
결국엔 개발자가 모든 소스코드에서 변경을 했어야 했는데.. 그렇게 하지 않아서
일부 웹서버에서의 쿼리가 이상하게 where조건없이 수행되었고 그래서 temp가
full 났던 것이랍니다.

vi sidhashsql.sql
set pages 1000
col sql_text format a120
select sql_text from v$sqltext_with_newlines
where hash_value=&hash_value order by piece;

SQL> @sidhashsql
Enter value for hash_value: 1126923165
old 2: where hash_value=&hash_value order by piece
new 2: where hash_value=1126923165 order by piece

SQL_TEXT

boan~~~~!!

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

아래 너무 자세하게 나와있죠?
No. 18484

TEMPORARY TABLESPACE에서 TEMPFILE 과 DATAFILE의 차이점 (8.1.X ~ 9I)
============================================================

PURPOSE

이 문서에서는 Oracle 7.3부터 사용되어 오던 create tablespace ... temporary
형태와, 8i부터 사용되는 create temporary tablespace... 의 차이점을 정리해
본다.
tablespace의 temporay type과 permanent type에 대한 비교는 <Bulletin#: 11938>
를 참조하도록 하고 여기에서는 permanent에 대해서는 논외로 한다.

Explanation

temporary segment가 생성 가능한 tablespace의 type과 temporary tablesapce에서
datafile과 tempfile의 차이점을 설명한다.

1. temporary segment를 생성가능한 tablespace type 정리

temporary tablespace의 tempfile과 datafile을 비교하기 전에, tablespace의
type들을 확인해 보고, 이 중 temporary segment가 생성될 수 있는 tablespace
type을 version별로 정리해본다.

tablespace는 7.2까지는 permanent type으로 dictionary managed방식으로
space를 할당/해제하던 방식만이 존재했다. db user의 temporary tablespace로
임의의 tablespace를 지정가능하였고, 해당 db user의 sort operation은
지정된 tablespace에서 발생하며, 다른 tablespace와 특별히 구분되는 것은
없었다.

이후, 7.3에 temporary type이 추가되고, 8i에서 locally managed type과 일반
datafile이 아닌 tempfile이 소개되면서 8i를 기준으로 기본적으로 다음과 같이
4가지 형태의 tablespace 형태가 가능하다.
이중 (1) ~ (3)번까지는 일반 datafile형태이고, (4)번의 경우는 이 문서에서
자세히 살펴볼 tempfile이다.
(locally managed와 dictionary managed의 차이점 및 사용 방법은
<Bulletin #: 18261>과 <Bulletin #: 11860> 참조)

(1) permanent-dictionary managed
(2) permanent-locally managed
(3) temporary-dictionary managed
(4) tempfile-locally managed

[주의] 위의 종류에 temporary datafile에 locally managed 형태의 tablespace는
없는것에 주의한다.
그리고 만약 system tablespace가 locally managed로 이미 생성된 경우에는
이후 모든 tablespace는 locally managed로 생성이 가능하고, dictionary
managed 형태는 생성하면 ORA-12913 (Cannot create dictionary managed
tablespace) 오류가 발생하게 된다.

이러한 여러가지 type의 tablespace중 temporary segment를 생성할 수 있는
tablespace에 제약이 존재한다.

- 8i: 어떠한 형태의 tablespace라도 db user의 temporary tablespace로 지정
가능하다. 단, permanent-locally managed 형태의 tablespace에 sort가
발생하게 되면 ORA-3212 (Temporary Segment cannot be created in
locally-managed tablespace) 오류가 발생하게 된다.

SQL> alter user scott temporary tablespace PERM_LOCAL;
User altered.

connect scott/tiger
SQL> select * from dept order by 1;
ORA-03212: Temporary Segment cannot be created in locally-managed
tablespace

- 9i: db user의 default temporary tablespace 지정 자체가 다음 두 가지
type만이 가능한다.

-temporary-dictionary managed
-tempile-locally managed

만약 permanent type의 tablespace를 db user의 tempoary tablespace로
지정하면, ORA-12911 (permanent tablespace cannot be temporary tablespace)
오류가 발생한다.

2. tempfile과 datafile의 비교

아래에서 tablespace지정시 tempfile과 datafile형태를 비교하게 되는데,
단, datafile형태의 경우 permanent type에 대해서는 언급하지 않는다.

(1) tempile의 특징

Oracle7.3에서 tablespace에 생성시 temporary option을 이용하여 생성되는
tablespace를 구성하는 화일은 datafile이다. 단지 이것이 기존의 permanent
type과 구별되는것은 이 tablespace에 생성되는 segment들이 매번 sort
operation마다 별도로 생성되는 대신, 하나의 segment로 만들어지면서
다른 session에서의 sort operation이 같은 segment를 공유하는 것이다.
(자세한 것은 <Bulletin#: 11938> 참조)

Oracle8.1부터 추가된 tempfile형태의 중요한 특징은 tempfile에 발생하는
변경사항은 redo log file에 기록되지 않는다는 것이다. tempfile에
checkpoint정보도 기록하지 않고 이에 따라 datafile recovery시에도
tempfile에 대해서는 recovery가 필요없게 된다.
이와 같은 이유로 standby database에서 read-only mode로 open하고
조회시 sort가 발생하여 tempfile이 변경되는것은 문제가 되지 않아
사용이 가능하다.

그리고 이미 앞에서 설명한 것과 같이 tempfile은 항상 locally managed
type으로만 생성이 되며, datafile형태의 temporary tablespace는 다음과
같이 locally managed type으로 생성 자체가 불가능하다.

SQL> create tablespace temp_datafile_local
2 DATAFILE '/ora/oradata/V920/temp_data.dbf' size 100M
3 TEMPORARY
4 EXTENT MANAGEMENT LOCAL UNIFORM SIZE 128K;

ORA-25144: invalid option for CREATE TABLESPACE with TEMPORARY contents


(2) temporary tablespace 생성 방법 비교

- tempfile형태의 경우
tempfile로 temporary tablespace를 생성하는 경우는 다음과 같이
생성하여야 하며, 반드시 locally managed 형태로만 생성 가능하다.

SQL> create TEMPORARY tablespace temp_tempfile_local
2 TEMPFILE '/ora/V920/temp_temp.dbf' size 100M
3 EXTENT MANAGEMENT LOCAL UNIFORM SIZE 128K;

아래 명령어에서 3번 line을 제거하고 생성하여도 default로 locally
managed로 생성이 되며, dictionary managed 형태로 생성하고자
3번 line대신 storage option을 추가하면
ORA-2180 (invalid option for CREATE TABLESPACE) 오류가 발생한다.

- datafile형태의 경우
다음과 같은 형태로 생성하게 되면, dictionary managed type의
temporary datafile형태로 tablespace가 만들어진다. 단, 9i의 경우
이미 앞에서 언급한대로 system tablespace가 locally managed인 경우에는
이와 같은 dictionary managed tablespace 생성은 ORA-12913이 발생하면서
불가능하게 된다.

SQL> create tablespace temp_datafile_dict
2 datafile '/ora/oradata/V920/temp_data.dbf' size 100M
3 TEMPORARY;

(3) dictionary view 의 차이

먼저 dba_tablespaces를 통해
SQL> select tablespace_name, contents, extent_management,
allocation_type from dba_tablespaces;

TABLESPACE_NAME CONTENTS EXTENT_MAN ALLOCATIO

TEMP_TEMPFILE_LOCAL TEMPORARY LOCAL UNIFORM
TEMP_DATAFILE_DICT TEMPORARY DICTIONARY

- tempfile의 경우

SQL> select STATUS, ENABLED, NAME from v$tempfile;

STATUS ENABLED NAME

ONLINE READ WRITE /ora/V920/temp_temp.dbf

SQL> select FILE_NAME, TABLESPACE_NAME from dba_temp_files;

FILE_NAME TABLESPACE_NAME

/ora/V920/temp_temp.dbf TEMP_TEMPFILE_LOCAL


- datafile 형태의 경우

다음과 같이 v$datafile과 dba_data_files를 통해 조회한다.

SQL> select STATUS, ENABLED, NAME from v$datafile;

STATUS ENABLED NAME

ONLINE READ WRITE /ora/oradata/V920/temp_data.dbf

SQL> select FILE_NAME, TABLESPACE_NAME from dba_data_files;

FILE_NAME TABLESPACE_NAME

/ora/oradata/V920/temp_data.dbf TEMP_DATAFILE_DICT

(4) tempfile의 삭제에 대해서

datafile의 경우 tablespace를 삭제하지 않고 datafile만 삭제하는 방법은
존재하지 않는다. 물론 alter database datafile 'filename' offline drop;
과 같은 command가 있지만 이것도 datafile을 데이타베이스에서 지워주는
것이 아니며 이렇게 offline drop된 datafile을 포함하는 tablespace는
recovery가 불가능한 경우라면 tablespace자체를 삭제해야 한다.

그런데 tempfile의 경우는 temporary tablespace는 그대로 유지한 채,
tempfile만 삭제하는 것이 가능하다.

SQL> alter database tempfile '/oradata/V817/temp_temp01.dbf'
2 drop;

8i의 경우라면 이와 같은 명령어 후 실제 directory로 이동하여 직접
tmep_temp01.dbf를 삭제하여야 한다.

9i에서는 drop뒤에 including datafiles 라는 option을 추가하여 tempfile의
drop시 바로 os상에서도 삭제되도록 할 수 있다.

SQL> alter database tempfile '/oradata/V817/temp_temp01.dbf'
2 drop including contents;

만약 이러한 방법으로, tempfile을 해당 temporary tablespace에서 모두
삭제한 경우, 실제 해당 tablespace에 disk sort가 필요하게 되면,
그때는 ORA-25153 (Temporary Tablespace is Empty) 오류가 발생하게 된다.

이때는 다음과 같이 임의의 tempfile을 다시 추가할 수 있다.

SQL> alter tablespace TEMP_TEMPFILE_LOCAL
2 add tempfile '/oradata/V817/temp_temp02.dbf';

Reference Documents

광주은행 안심클릭 DB 작업

### default temp 파일로 생성되어 있을 경우 아래처럼 drop 후 추가하면 됨
SQL> alter database tempfile '/logs/oradata/temp01.dbf' drop;

Database altered.

SQL> alter tablespace TEMP add tempfile '/logs/oradata/acsdb/temp01.dbf' SIZE 100M;

Tablespace altered.

### datafile type으로 temp 생성 되어 있을 경우
SQL> CREATE TEMPORARY TABLESPACE TEMP02 TEMPFILE '/logs/oradata/temp02.dbf' SIZE 100M
Tablespace created.
SQL> alter user VISA3D temporary tablespace TEMP02;
SQL> alter tablespace TEMP offline;
Tablespace altered.

SQL> drop tablespace temp;
Database droped.


### DATA 파일 이동
SQL> ALTER TABLESPACE USER_DATA RENAME DATAFILE '<OLD FILE>' TO '<NEW FILE>';

Posted by redkite
, |

No. 11747

RAW DEVICE와 FILE SYSTEM 간에 오라클 데이터화일 이동하기
======================================================

유닉스 명령이 dd를 이용하여 오라클 데이터화일을 Unix File System과 Raw
Device 간에 이동할 수 있으나, 플랫폼 별 Raw Device의 특성으로 인하여 주의할
점이 있다. 만일 잘못된 이동으로 인하여 데이터베이스가 기동하지 못하면,
ORA-7366 (sfifi: invalid file, file does not have valid header block.)
에러가 발생할 수 있다.

예를 들어 Digital unix의 경우는 raw device에 64k OS 헤더가 필요하므로 dd
명령어 옵션 중 iseek와 oseek를 활용하여야 한다.

다음은 예제를 통하여 데이터화일을 Raw Device에서 Unix File System으로
이동하는 절차이다.

(운영 현황)

- 현재의 위치: /dev/rdsk/c0t15d0s7
- 이동할 위치: /oracle/file/system.dbf
- 화일의 크기: 488636416 bytes <--- V$DATAFILE.BYTES column 값!
- DB_BLOCK_SIZE: 2048 bytes


(준비 단계)

1. Oracle 블럭 수 계산:

BYTES / DB_BLOCK_SIZE = 488636416 / 2048 = 238592 (블럭)

2. O/S file header 블럭 추가:

238592 + 1 = 238593 (블럭)
: "ls -l /oracle/file/system.dbf" 명령으로 확인 가능하며, O/S file
header는 1블럭으로 항상 일정함.

3. Raw Device OS header 블럭 계산: raw device (os block) header size

64K / DB_BLOCK_SIZE = 65536 / 2048 = 32 (블럭)
: 사용할 dd 명령어 중 블럭의 크기를 DB_BLOCK_SIZE(2048바이트)로 할
예정이므로 2048로 나누어야 함.

(명령어 형식)

$ dd if=<raw device> of=<UFS file> bs=<oracle blocksize>
iseek=<blocks to skip> count=<total count>

(명령어 수행 절차)

(1) SVRMGR> STARTUP MOUNT
(2) SVRMGR> !dd if=/dev/rdsk/c0t15d0s7 of=/oracle/file/system.dbf bs=2048 iseek=32 count=238593
(3) SVRMGR> ALTER DATABASE RENAME FILE '/dev/rdsk/c0t15d0s7' TO
'/oracle/file/system.dbf';
(4) SVRMGR> ALTER DATABASE OPEN;

========================================================================

반대로 Unix File System에서 Raw Device로 이동하는 명령어 형식은 아래와 같다.

(명령어 형식)

$ dd if=<UFS file> of=<raw device> bs=<oracle blocksize> \
oseek=<blocks to skip> count=<total count>

유사한 방식으로 데이타 화일 뿐 아니라 리두 로그 화일도 이동할 수 있다.

[주의] Raw Device의 블럭 헤더의 크기는 OS마다 다를 수 있으므로 플랫폼
벤더사에 미리 확인한 후 작업하여야 한다.

[출처] RAW DEVICE FILE SYSTEM 간에 오라클 데이터화일 이동하기 (ProDBA) |작성자 산타

'01.오라클 > 002.DB 마이그레이션' 카테고리의 다른 글

[오라클]Characterset 변경  (0) 2013.02.20
[오라클]Full export / import  (0) 2013.02.20
[오라클]Undo Tablespace 변경  (0) 2012.12.19
[오라클]Voting Disk 이관  (0) 2012.12.19
[오라클]Templorary File 변경  (0) 2012.12.19
Posted by redkite
, |

최근에 달린 댓글

최근에 받은 트랙백

글 보관함