블로그 이미지
redkite

카테고리

분류 전체보기 (291)
00.SI프로젝트 산출물 (0)
00.센터 운영 문서 (0)
01.DBMS ============.. (0)
01.오라클 (117)
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
, |

Data Pump (Master Table)

      1) External Table 확장
      2) expdp, impdp
      * DB Link를 이용한 Network Mode (NETWORK_LINK 옵션)
      * Directory Object가 반드시 필요(DIRECTORY 옵션)
      * expdp 옵션에 의한 객체 단위 포함/제외 가능(EXCLUDE/INCLUDE 옵션 및 향상된 QUERY 옵션)
      * 제한적이긴 하지만 Parallel 가능(PARALLEL 옵션)
      * Master Table에 의한 중지 작업 재시작 및 작업 변경(추가 및 삭제)이 가능
      * REMAP_SCHEMA, REMAP_DATAFILE, REMAP_TABLESPACE 등 새로운 옵션

## 실습 01 ######################################################################

sqlplus system/oracle  또는 conn system/oracle

host mkdir C:\oracle10g\EXP_PUMP1
host mkdir C:\oracle10g\EXP_PUMP2

CREATE OR REPLACE DIRECTORY exp_pump_dir1 AS 'C:\oracle10g\EXP_PUMP1' ;
CREATE OR REPLACE DIRECTORY exp_pump_dir2 AS 'C:\oracle10g\EXP_PUMP2' ;

grant read, write on directory exp_pump_dir1 to public ;
grant read, write on directory exp_pump_dir2 to public ;

exit


cd c:\oracle10g\exp_pump

1)
expdp hr/hr DUMPFILE=exp_pump_dir1:exp_hr03.dmp LOGFILE=exp_pump_dir2:exp_hr03.log

expdp hr/hr DUMPFILE=exp_pump_dir:expdp_hr01.dmp NOLOGFILE=y

2)                                                                 
expdp hr/hr DIRECTORY=exp_pump_dir1 DUMPFILE=exp_hr02.dmp LOGFILE=exp_pump_dir2:exp_hr02.log

3)
set DATA_PUMP_DIR=exp_pump_dir

expdp system/oracle DUMPFILE=exp_hr_emp01.dmp NOLOGFILE=y tables=hr.employees
expdp system/oracle DUMPFILE=exp_hr05.dmp LOGFILE=exp_hr04.log SCHEMAS=hr


## 실습 02 expdp impdp 기본 옵션 ################################################

(실습 준비)

mkdir c:\oracle10g
mkdir c:\oracle10g\dptest

cd c:\oracle10g\dptest
sqlplus /nolog
conn sys/oracle as sysdba

create directory dp_test_dir as 'c:\oracle10g\dptest' ;

grant read, write on directory dp_test_dir to hr ;

conn hr/hr

create table emps03_02 tablespace example
as
  select * from hr.employees ;

insert into emps03_02 select * from emps03_02 ; --> 12회 정도 실행

commit ;

select sum(bytes)/1024/1024 AS "SIZE_MB" from user_segments
where  segment_name = 'EMPS03_02' ;

conn system/oracle

alter system checkpoint ;

exec dbms_stats.gather_table_stats('HR','EMPS03_02' -
     ,estimate_percent => dbms_stats.auto_sample_size -
     ,method_opt => 'FOR ALL COLUMNS SIZE AUTO' , cascade => TRUE) ;

select sum(bytes)/1024/1024 AS "SIZE_MB" from dba_segments
where  owner='HR' and segment_name = 'EMPS03_02' ;

exit

------------------------------------------------------------------------
## exp_test01_par01.txt 파일 작성

userid=hr/hr
directory=dp_test_dir
job_name=exptest01
logfile=exp_test01.log
filesize=2M
tables=emps03_02
estimate=statistics
estimate_only=y           <- 실제로 익스포트 안받고 확인받하는거야? 사용공간 분석이야

- 아래 애는 절대경로를 사용한다..
expdp parfile=exp_test01_par01.txt

------------------------------------------------------------------------
## exp_test01_par02.txt 파일 작성

userid=hr/hr
directory=dp_test_dir
job_name=exptest0102
logfile=exp_test0102.log
filesize=5M
tables=emps03_02
dumpfile=exp_test02_%U.dmp

expdp parfile=exp_test01_par02.txt

------------------------------------------------------------------------
## imp_test01_par03.txt 파일 작성

userid=hr/hr
directory=dp_test_dir
job_name=imptest0103
logfile=imp_test0103.log
tables=emps03_02
dumpfile=exp_test02_%U.dmp
table_exists_action=append


sqlplus system/oracle
truncate table hr.emps03_02 ;
exit

impdp parfile=imp_test01_par03.txt


## exp_test01_par04.txt  파일 작성

userid=hr/hr
directory=dp_test_dir
job_name=exptest0104
logfile=exp_test0104.log
filesize=5M
dumpfile=exp_test04_%U.dmp
EXCLUDE=VIEW
EXCLUDE=PACKAGE
EXCLUDE=INDEX:"LIKE 'EMP_%'"
EXCLUDE=TABLE:"LIKE 'EMPS03%'"
EXCLUDE=TABLE:"LIKE 'JOB%'"
QUERY=HR.employees:"WHERE department_id IN (10,20) and salary<1600"

expdp parfile=exp_test01_par04.txt


(참고)
CONTENT=METADATA_ONLY
CONTENT=DATA_ONLY
CONTENT=ALL

 

## 실습 03 Attach & JOB STOP & JOB RESTART ######################################

(준비작업)

sqlplus hr/hr

select sum(bytes)/1024/1024 AS "SIZE_MB" from user_segments
where  segment_name = 'EMPS03_02' ;

insert into emps03_02 select * from emps03_02 ; <--2회 실행

commit ;

conn system/oracle

alter system checkpoint ;

exit

## 작업내용 확인(현재 진행중이거나, 에러 후 중단된 작업내역을 확인가능.)

sqlplus /nolog
conn sys/oracle as sysdba

grant select on dba_datapump_jobs to hr ; <--조회 권한할당

conn hr/hr

desc dba_datapump_jobs

col OWNER_NAME format a10
col JOB_NAME format a15
col OPERATION format a15
col JOB_MODE format a10
col STATE format a15
set linesize 120

select * from dba_datapump_jobs ;

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

(SESSION 1)--------------------------------------------------------

## exp_test02_par01.txt 파일 작성

userid=hr/hr
directory=dp_test_dir
job_name=exptest0201
logfile=exp_test0201.log
filesize=30M
tables=emps03_02
dumpfile=exp_test0201_%U.dmp

sqlplus hr/hr


(SESSION 2)--------------------------------------------------------
cd c:\oracle10g\dptest
expdp parfile=exp_test02_par01.txt


(SESSION 1) 작업확인-----------------------------------------------

select * from dba_datapump_jobs ;  <--JOB_NAME 필드 확인


(SESSION 3) <--현재 작업중인 export에 연결.------------------------

expdp hr/hr attach=exptest0201  <--job이름

Export>


(SESSION 1)--------------------------------------------------------

select * from dba_datapump_jobs ;  <--ATTACHED_SESSIONS 수가 증가

(SESSION 3) 현재 작업 중단-----------------------------------------

Export> stop_job

yes 입력 --> 시간걸림 그동안에 다음 수행


(SESSION 1)

select * from dba_datapump_jobs ;  <--ATTACHED_SESSIONS 수가 감소

그 동안에 (SESSION 3) 중단 작업 완료
   --> 원래 SESSION 2도 중단됨

(SESSION 2) 강제 종료

(SESSION 1)

select * from dba_datapump_jobs ;  <-- NOT RUNNING

===================================================================
## 중단작업에 attach 및 작업 재시작 실습
===================================================================

(SESSION 3)

expdp hr/hr attach=exptest0201  <--job이름

Export>

(SESSION 1)

select * from dba_datapump_jobs ;


(SESSION 3) 중단 작업 재개

Export> start_job

Export> status=10  <-- 매 10초간 상태 확인

Export> continue_client <-- Session 2에서 시작된 작업인데 클라이언트가 종료되었으므로
                            Session 3에서 진행 결과를 받도록 설정.

작업완료 후에

(SESSION 1)

select * from dba_datapump_jobs ;

 

 

DBA_DATAPUMP_JOBS

>DBA_DATAPUMP_JOBS identifies all active Data Pump jobs in the database, regardless of their state, on an instance (or on all instances for Real Application Clusters). It also show all Data Pump master tables not currently associated with an active job.

Related View

>USER_DATAPUMP_JOBS displays the Data Pump jobs owned by the current user. This view does not display the OWNER_NAME column.

Column Datatype NULL Description
OWNER_NAME VARCHAR2(30)   User that initiated the job
JOB_NAME VARCHAR2(30)   User-supplied name for the job (or the default name generated by the server)
OPERATION VARCHAR2(30)   Type of job
JOB_MODE VARCHAR2(30)   Mode of job
STATE VARCHAR2(30)   Current job state
DEGREE NUMBER   Number of worker processes performing the operation
ATTACHED_SESSIONS NUMBER   Number of sessions attached to the job
DATAPUMP_SESSIONS NUMBER   Number of Data Pump sessions participating in the job

Posted by redkite
, |

### 백업 본 설정 및 복구(*** MDF  파일 삭제 된 후 마지막 Tailog--트랜잭션 로그 백업 필히 작업 후 복구 작업 시작)

** 복구 모델 전체 / 단순(트랜잭션 로그는 백업 안됨--noarchive mode)


drop database zDB

go


create database zDB

go

use zdb

go

create table T1 (id int)

go

-- 0. 백업폴더 생성

insert into T1 values (10),(20),(30)

select * from T1

go

-- 1. 전체백업

insert into T1 values (40),(50),(60)

select * from T1

go

-- 2. 차등백업

insert into T1 values (70),(80)

select * from T1

go

-- 3. 로그백업

insert into T1 values (90),(100)

select * from T1

go

-- 4. 차등백업

insert into T1 values (200),(300)

select * from T1

go


-- 장애

 - 데이터베이스 오프라인


 alter database zDB set offline


 - zDB.mdf 삭제

 - 데이터베이스 온라인


alter database zDB set online


-- Tail-Log 백업 ********


 backup log zDB to disk='c:\drive\zDB_last3.bak'

with no_truncate, init --(비상시백업,백업매체초기화)

-- 복원


-- 1. 기존 백업본을 통한 복원 (옵션: With norecovery)

--> 복원중 표시되고, 뒤에 복원을 또 할 수 있음.

-- 2. Tail-Log 백업본을 통한 복원 (옵션: With recovery)

--> 복원 완료를 의미, 뒤에 복원을 할 수 없음.

-- 확인

use zDB

select * from T1




## Shrink 테스트


ShrinkLog.sql





 ### 잠금의 단위

 

 - RID : 테이블에 있는 한 행을 잠그기 위한 행 ID입니다. 

 - 키(Key) : 인덱스에 있는 행 잠금입니다. 

 - 페이지(Page) : 8킬로바이트(KB) 데이터 페이지 또는 인덱스 페이지입니다. 

 - 익스텐트(Extent) : 인접한 여덟 개의 데이터 페이지 또는 인덱스 페이지 그룹입니다. 

 - 테이블(Table) : 모든 데이터와 인덱스가 포함된 전체 테이블입니다.  

 - 데이터베이스(DB) : 데이터베이스입니다. 




 ### 잠금의 종류


 - 공유(S) : (Shared Lock) SELECT 문처럼 데이터를 변경하거나 

업데이트하지 않는 작업(읽기 전용 작업)에 사용합니다. 

공유 잠금을 형성하여 다른 트랜잭션에 의해 현재의 데이터가 

데이터가 변경되지 못하도록 합니다.  


 - 업데이트(U) : (Update Lock) 데이터를 UPDATE 하기 위해 

Exclusive Lock을 형성하기 전에 미리 걸어주는 잠금입니다. 

즉, "곧 변경할테니까 접근하지 마라!" 라는 의미로 보시면 됩니다.  


 - 단독(X) : (Exclusive Lock)  INSERT, UPDATE, DELETE와 같은 

데이터 수정 작업에 사용합니다. 

여러 개의 업데이트 작업이 같은 리소스에 대해 동시에 

이루어지지 못하게 합니다.

데이터 읽기 조차도 못하게 됩니다. 


 - 내재 : (Intent Lock)  잠금 계층 구조를 만드는 데 사용합니다. 

내재된 잠금의 종류에는 내재된 공유(IS) 잠금, 

내재된 단독(IX) 잠금, 공유 및 내재된 단독(SIX) 잠금이 있습니다. 

예를 들어 레코드에 공유잠금(S)이 형성되어 있으면 

이 레코드를 포함하는 테이블은 내재된 공유잠금(IS)를 형성하여 

"레코드에 공유 잠금이 형성되어 있으니 너희들은 나에게 

단독 잠금(Exclusive Lock) 걸면 안돼!" 라고 알려주는 것입니다. 


 - 스키마 : (Schema Lock)  테이블의 스키마에 종속되는 작업이 실행될 때 사용합니다. 

스키마 잠금의 종류에는 스키마 수정(Sch-M)과 스키마 안전성(Sch-S) 

두 가지가 있습니다.  


 - 대량 업데이트(BU) : (Bulk Update Lock) 데이터를 테이블로 

대량 복사하는 경우와 TABLOCK 참고가 지정된 경우 사용합니다. 





 ### 고립화 수준(Isolation Level) 


 - 아직 UPDATE가 완료 되지 않았기 때문에 UPDATE 되기전 


잘못된 데이터를 읽을 위험이 있으므로 이를 방지하기 위함입니다. 


하지만 원한다면 UPDATE 작업이 완료되지 않은 상태의 데이터를 


다른 세션에서 읽을 수 있도록 할 수 있습니다.



 - 트랜잭션의 고립화 수준이란 여러개의 트랜잭션이 동시에 수행 될 때 


잠금 충돌이 발생 하면 이를 어떻게 처리할지에 대한 문제라고 보시면 됩니다. 


고립화 수준을 어떻게 하느냐에 따라 다른 결과를 볼수 있게 됩니다.



 - 두 세션의 잠금 현상을 이용해보도록 하겠습니다. 


한 세션이 UPDATE 중일 다른 세션은 이 UPDATE 작업이 완료 될때까지 


그 데이터를 대상으로 검색을 할 수가 없었습니다. 


왜냐하면 현재 진행중인 UPDATE 작업이 COMMIT 될 지 


ROLLBACK 될 지 아직 모르기 때문에 완벽하지 않은 데이터를 보는것을 


방지하도록 하기 위해서입니다. 


하지만 다음과 같이 트랜잭션의 고립화 수준을 별도로 지정하게 되면 


결과는 달라집니다.



  --> SET TRANSACTION ISOLATION LEVEL 

   READ UNCOMMITTED


   GO 



 


 ### 고립화 수준(Isolation Level)의 종류


 - 고립화 수준은 낮을 수록 성능은 좋아집니다. 


하지만 데이터의 무결성은 깨어질 가능성이 높습니다. 


트랜잭션의 고립화 수준에는 다음과 같이 4가지 종류가 있습니다.



 1) READ UNCOMMITTED

  : Trouble

 - DirtyRead

 - NonRepeatable Read

 - Phantom Read


고립화 수준에서 가장 낮은 수준입니다. 


즉, DIrty Page를 읽어오게 되는 것입니다. 



2) READ COMMITTED (Default)

: Trouble

 - NonRepeatable Read

 - Phantom Read


  Dirty Page를 읽는, 즉 DIrty Read를 방지합니다. 


  별도의 고립화 수준을 설정하지 않았거나 

READ COMMITTED를 설정하게 되면 


  COMMIT 하지 않은 트랜잭션이 이용한 자원에 대해 

트랜잭션이 완료되어야 


(= 잠금이 해제되어야) 데이터를 읽을 수 있습니다.



3) REPEATABLE READ

: Trouble

 - Phantom Read


SQL Server는 기본적으로 같은 값을 반복적으로 가져 올 경우 이전 값과 


항상 같다는 것을 보장하지 못합니다. 


이러한 것을 Nonrepeatable Read라고 하는데 이러한 문제는 


한 트랜잭션 내에서 같은 SQL문을 여러번 사용할 경우 내부적으로 


공유 잠금(S)를 트랜잭션 종료시까지 유지하지 않기 때문입니다. 


REPEATABLE READ 고립화 수준은 이러한 문제를 해결할 수 있는 고립화 수준입니다. 


트랜잭션이 완료될 때까지 공유 잠금을 유지하여 여러번 같은 데이터를 읽어도 


항상 같은 값이 얻어지도록 합니다.




주의해야할 사항은 REPEATABLE READ가 설정되면 


원래 읽었던 데이터에 대하여서는 항상 같은 값이 유지 되지만 


새로 추가되는 데이터를 막을 수는 없습니다. 



예를 들어 특정 조건에 만족한 레코드가 5개였으면 


이 5개의 레코드는 언제든 같은 값을 보이게 되지만 


다른 트랜잭션에 의해 이 조건을 만족하는 새로운 레코드가 추가되면 


원래 없었던 새로운 레코드가 보이게 됩니다. 


이러한 것을 Pantom Read라고 합니다.





4) SERIALIZABLE

: Trouble

 - Nothing


가장 높은 고립화 수준으로 REPEATABLE READ 


고립화 수준이 막지 못하는 Phantom Read까지 방지해줍니다. 


완벽한 데이터베이스의 일관성은 유지해 주지만 


잠금을 유지하기 위하여 오버헤드는 증가하게 됩니다.


### 잠금크기와 관련된 잠금힌트


1) ROWLock : 공유 행 잠금

2) PAGLock : 공유 페이지 잠금

3) TABLock : 공유 테이블 잠금

4) TABLockX : 단독(Exclusive) 테이블 잠금


### 그밖의 잠금힌트


1) XLock : 단독(Exclusive)잠금 지정

2) UpdLock : 업데이트 잠금 지정

3) ReadPast : 잠긴 행은 건너뛰고 잠기지 않는 행들만 접근 

-> Read Commited 격리수준에서만 적용


### 커서(Cursor)에 대한 요약 정리

커서란?

- 데이터 처리는 집합단위로 이루어지기도 하지만 조건에 따라서는 행 단위로 처리하기도 한다.

- 행 단위의 데이터 처리시 커서를 사용한다.


커서의 장점

- 데이터를 행 단위로 처리할 수 있음.


커서의 단점

- 데이터 처리 속도가 느려짐.(SQL문에 비해 느림)


1.1 커서의 종류

- 서버커서(Server Cursor), 클라이언트 커서(Client Cursor)


서버커서(Server Cursor)

- T-SQL 커서와 API 커서로 나뉨


T-SQL 커서 란?

- 결과 집합을 만드는 T-SQL스크립트, 트리거, 저장 프로시저에서 사용

- 변수로 한 열을 할당받는다.(변수의 크기는 열의 데이터 타입과 데이터를 모두 받을 수 있을 만큼 선언)


API 커서란?

- OLEDB, ODBC, ADO를 이용하여 SQL 문의 결과 집합에서 커서 매핑.


클라이언트 커서란?

- ODBC에서 지원하는 커서, 결과 집합을 클라이언트 캐쉬에 저장(읽기전용)


1.2 커서의 작업

- DECLARE를 이용한 커서 선언

- OPEN을 이용한 커서 열기

- FETCH를 이용한 데이터 불러오기

- CLOSE를 이용한 커서 닫기

- DEALLOCATE를 사용ㅇ한 커서 선언 제거


1.3 커서의 ANSI 문법

- Declare 커서 이름 [ INSENSITIVE ] [ SCROLL ] CURSOR

   FOR SELECT 구문

   [ FOR { READONLY | UPDATE [ OF 컬럼명 [......N]] } ]


- INSENSITIVE : 커서에서 사용할 데이터를 임시로 복사해 주는 커서를 정의

                커서에서 정의된 데이터는 tempDB에 저장됨.

                잠금이 생김, 동시성 저하.

- SCROLL : 모든 인출 옵션 사용이 가능

           인출 옵션(FIRST, LAST, PRIOR, NEXT, RELATIVE, ABSOLUTE)

           인출 옵션이란? 데이터를 불러올 행을 이동하는 방식


- SELECT 구문 : 일반적인 select 구문 형식을 따름

- READ ONLY : 커서를 통한 데이터 변경 및 삭제를 방지, DELETE, UPDATE 기능을 무시.


1.4 커서의 T-SQL 문법

- DECLARE 커서 이름 CURSOR [ LOCAL | GLOBAL ]

 [ FORWARD_ONLY | SCROLL ]

 [ STATIC | KEYSET | DYNAMIC | FAST_FORWARD ]

 [ READ_ONLY | SCROLL_LOCKS | OPTIMISTIC ]

 [ TYPE_WARING ]

 FOR SELECT 구문

  [ FOR UPDATE [ OF 컬럼명 [ ,......N]]]


- LOCAL: 커서의 범위를 로컬로 지정(로컬변수)

- GLOBAL: 커서의 범위를 전역을 지정(전역변수)

- FORWARD_ONLY: "전진만 있되 후퇴는 없도다.", 유일한 명령 옵션은 FETCH_NEXT

- SCROLL: 모든 인출 옵션(FIRST, LAST, PRIOR, NEXT, RELATIVE, ABSOLUTE)를 사용하도록 지정

- STATIC: 수정이 안됨(임시커서)

- KEYSET: 커서에 포함되는 행과 멤버와 순서가 고정되도록 지정.

- DYNAMIC: 인출할 때 마다 행의 데이터 값과 순서, 멤버가 변경됨, 동적 커서

- FAST_FORWARD: 성능 최적화가 설정된 FORWARD_ONLY, READ_ONLY 커서를 지정.

- READ_ONLY: 데이터에 대한 변경 및 삭제 방지, UPDATE, DELETE 구문의 WHERE CURRENT OF 절에서 이키를 사용할 수 없음

- SCROLL_LOCKS: 위치 지정 업데이트나 삭제가 성공하도록 지정


-- Declare 구문지정

DECLARE YearPlan_Cur CURSOR FOR

  SELECT CustCode, WkCnt, DeptCode, Week, Day, SMethodYN, DaN

  FROM RM_YearPlan

  WHERE WkCnt = '1'


-- OPEN 구문

OPEN YearPlan_Cur


-- FETCH 구문

FETCH NEXT FROM YearPlan_Cur

WHILE @@FETCH_STATUS = 0

 BEGIN

  FETCH NEXT FROM YearPlan_Cur

 END


-- CLOSE 구문

CLOSE YearPlan_Cur


-- 커서 해제

DEALLOCATE YearPlan_Cur



Cursor.sql



Posted by redkite
, |

최근에 달린 댓글

최근에 받은 트랙백

글 보관함