블로그 이미지
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

달력

« » 2013.4
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

공지사항

최근에 올라온 글

find 의 -perm 옵션은 보통 3가지 mode 를 사용합니다.

  1. -perm mode
  2. -perm -mode
  3. -perm /mode

mode 는 정확하게 mode 가 매치되는 것만

-mode 는 mode 를 포함하고, 추가적인 퍼미션이 있는 것만

/mode 는 mode 에서 한개 bit라도 매치되는 것이 있으면

아래의 예들을 실행해 보시면 이해에 도움이 되실 겁니다.

하나의 임시 디렉토리 속에 아래 명령으로 모든 가능한 퍼미션을 만들고 테스트 해보세요.

for i in $(seq 0 7); do for j in $(seq 0 7); do for k in $(seq 0 7); do  touch ${i}${j}${k}; chmod ${i}${j}${k} ${i}${j}${k}; done; done; done

아래는 서로 결과가 같고, 퍼미션이 0700인 것만 찾습니다.

find . -perm u+rwx

find . -perm u=rwx

find . -perm 0700

find . -perm 700

아래는 서로 결과가 같고, 퍼미션이 0020인 것만 찾습니다.

find . -perm g+w

find . -perm g=w

find . -perm 0020

find . -perm 020

find . -perm 20

아래는 서로 결과가 같고, 퍼미션이 0500 보다 더 많이 허용된 것을 찾습니다.

find . -perm -u+rx

find . -perm -u=rx

find . -perm -0500

find . -perm -500

아래는 서로 결과가 같고, 퍼미션 0771 의 각 권한(rwxrwxrwx) 중 한 개 이상의 권한이 같은 것을 찾습니다.

find . -perm /u+rwx,g+rwx,o+x

find . -perm /u=rwx,g=rwx,o=x

find . -perm /u=rwx,g=rwx,o+x

find . -perm /0771

find . -perm /771

아래와 같이 !을 붙일 때 찾을 수 있는 퍼미션의 예상은

find . ! -perm /u+rwx,g+rwx,o+x -ls

-------rw-

--------w-

----------

-------r--

입니다.

참조하세요 ^^

추가질문에 대한 답변

-perm -2 -o -perm -20

-o 는 or 의 의미입니다.

-perm -2 또는 -perm -20 입니다.

other 가 writable 이상이거나 또는 group 이 writable 이상인 것을 의미합니다.

즉, other 또는 group 에 실행권한이 있는 파일을 의미합니다.

같은 의미지만 반대로 이야기 하면, 실행권한이 user 에게만 있거나 아예 없는 파일을 제외한 파일을 의미합니다.

만약,

find ../ ! -user mylin \( -perm 2 -o -perm -20 \) -exec {} \; 이라면

상위 디렉토리의 하위로 소유자가 user가 아니고 other나 group 에 실행권한이 있는 파일을 찾아서 실행한다

는 의미가 됩니다.

 

'02.서버-Linux' 카테고리의 다른 글

[리눅스]CentOS virbr0 NAT disable  (0) 2013.05.08
[리눅스]멀티 환경변수 case 문 이용  (0) 2013.03.29
[리눅스]RPM Failed dependencies  (0) 2013.03.28
[리눅스]NDD & TCPDUMP  (0) 2013.03.25
[리눅스]SoftWare RAID10  (0) 2013.03.18
Posted by redkite
, |

Service management details

svcs(1) command

System administrators can more easily monitor services using Solaris Service Manager’s service status information and service activation/deactivation interfaces based on the commands (svcs(1), svcadm(1) etc). Until Solaris 9, it was a complicated procedure to understand service status. Service level information was not provided and system administrators have to assume service status from their own analysis of kernel level information. A slow and error prone process.

svcadm(1M) command

Services and the services on which they depend are started in their appropriate order using the Solaris Service Manager svcadm(1) command. System administrators are longer required to run complicated service startup operations.

For example, if there are two services, Service A and Service B, and Service A depends on Service B, previously the system administrator needed to start the services paying close attention to their dependent relationship. Now with Solaris10, they only have to start Service A. Solaris Service Manager automatically detects that Service B needs to be started, and starts the services in the right sequence.

사용자 삽입 이미지

With Solaris 10 the traditional service stop procedure using the kill(1) or pkill(1) commands is no longer available. This is because, once stopped, Solaris Service Manager will automatically restart them. So a new command, svcadm (1M) is now used for stopping services.

References
 Solaris 9 or earlier versionsSolaris 10
Service statusps(1) command 
(only process information is shown)
svcs(1) or ps(1) command
Service stop# /etc/init.d/cron stop# svcadm disable -t 
system/cron:default
Service restart (temporary)# /etc/init.d cron start# svcadm enable -t 
system/cron:default
Service stop 
After service restart the service isn't started
(1)# /etc/init.d/cron stop 
(2)# mv /etc/rc2.d/S75cron /etc/rc2.d/_S75cron 
(Need to rename the service start script)
# svcadm disable -t 
system/cron:default
Service restart (permanent)(1) # /etc/init.d/cron stop 
(2) # /etc/init.d/cron start
# svcadm restart -t 
system/cron:default


- Solaris 10 간단한 재실행
# svcs cron
STATE          STIME    FMRI
online          4월_26  svc:/system/cron:default
svcadm restart cron
#
# svcs cron
STATE          STIME    FMRI
online         11:26:41 svc:/system/cron:default

Posted by redkite
, |

sendmail은 목적지를 확인하지 못한 메일을 clientmqueue에 임시로 저장했다가 목적지가 확인되면 mqueue로 보내서 메일을 발송하는 거라고 한다. 그런데 sendmail을 사용하지 않는 시스템에서 이러한 일이 발생하는 것은 logwatch에서 주요로그보고서를 메일로 발송하는 것 때문에 이러한 문제가 발생한다고 한다.

 

logwatch의 메일발송기능을 없애려면 /etc/contab의 내용에서 MAILTO=root의 내용에서 root로 지정된것을 뺴주면 된다고 한다.

 

엄청나게 많은 파일이 생긴 clientmqueue디렉토리는 한번에 지우기가 어려운데 아래의 명령으로 한번에 지울수 있다고 한다.

해당 디렉터리로 이동 후 아래 명령을 실행한다.
ls | xargs rm -f

 

아니면, 아예 폴더 자체를 날려버리고 새로 만들어도 상관 없다.

rm -rf /var/spool/clientmqueue

mkdir /var/spool/clientmqueue

chown smmsp.smmsp /var/spool/clientmqueue

 

주기적으로 지워지게 crontab에 삭제 명령어를 등록할 수도 있따.

$ crontab -e
30 0 * * * /usr/bin/find /var/spool/clientmqueue -mtime +30 | xargs rm -f 

Posted by redkite
, |

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
, |

### INDEX 생성 시

1) 조회 빈도

2) 데이터 입력이 빈번한가


3) 범위형 쿼리(CI 가 좋음)

4) 포인트 쿼리(CI/NCI 관게 없음)

5) 사이즈


### INDEX  활용

 1)업무분석


 - 조회컬럼

 - 정렬컬럼

 - 컬럼에 대한 프로세스 


 2) 인덱스가 걸리는 컬럼의 사이즈


 - 컬럼의 사이즈 -> 데이터페이지 -> CI의 인덱스 페이지 (CI의 키값)

-> NCI 의 인덱스 페이지


 3) 한 테이블의 컬럼의 숫자를 고민해보세요 


 - Lock, Dead Lock


 4) 복합인덱스 => 검색 데이터 사용량 빈도 ?


 - '풍물'동아리에 있는 학생의 수 => 동아리 코드 + 학생번호

 - '홍길동'학생이 가입한 동아리의 수 => 학생번호 + 동아리코드


 5) 커버드 쿼리의 이용을 고민해보자


 - 커버드 쿼리 : 조회의 조건과 대상 컬럼이 인덱스에 있고,

그 인덱스로 질의를 하는 것


 - Size와 페이지분할

<- 복합인덱스(4)

<- 커버드쿼리(2+2)


 6) 파일그룹을 이용하자


 - 파일그룹을 이용해서 분한테이블/분할인덱스를 만듦으로써


   한개의 테이블에 걸리는 인덱스의 높이/깊이를 


   감소시키면서 성능을 향상시킨다


 7) 인덱스 활용쿼리 디자인


 - 인덱스가 정의된 열을 가공하지 말아야 한다

 - Like 키워드의 검색문자열 앞에 와일드 카드 사용을 피한다



### Index 생성 고려사항


 1. 조회가 빈번하게 일어나지 않는 테이블에 Index 생성하지말것


 2. Where 절 뒤에 오는 컬럼을 대상으로 Index를 고려해야 함


 3. 밀도가 높은 컬럼은 Index를 걸지 말것 예)성별[남,녀]


 4. Index를 재구성, 재작성을 통해서 재정렬을 할수 있음


- 재구성 (Re-Organization) : 리모델링

- 재작성 (Re-Build)   : 재건축


 5. Index 를 설정한다고 해도 반드시 Unique 한것은 아니다


 6. PK는 Clustered Index를, UQ는 Non-Clustered Index가 기본적으로


설정된다


 7. Index가 필요하다면,


포인트 쿼리, 범위쿼리, 추가(순차적/비순차적), 크기


 8. Clustered Index 

- 범위쿼리와 순차적 Data입력/수정/삭제에 바람직

- Table당 한개만 생성 가능


 9. Non-Clustered Index

- 비순차적 Data입력/수정/삭제와 포인트쿼리에 바람직

- Table당 249개 생성 가능


10. Index Key 설정 시, 같은 조건이면 크기(Size) 작은 것으로 할것


11. Scan/Seek


- Table Scan : Heap의 상태에서 전체 페이지 조회

- Clustered index Scan : CI로 설정된 상태에서 전체

페이지 조회


- Clustered index Seek : CI로 설정된 상태에서 

Index를 통한 조회


- Index Seek : NCI로 설정된 상태에서 Index를 통한 조회


12. 외래키(Foreign Key)에 Index를 설정할 때, 성능이 좋아질 

확률이 많다


13. alter index 지원은 SQL Server 2005 부터 가능


14. 단일컬럼 Index 


- 복합 컬럼 index : 설정된 컬럼 모두 Key값


create nonclustered index idx_cust_N

on cust_N (customerid,추가컬럼)



- 포괄열 index    : 포괄열은 Key값은 아님

 : NCI 에서만 가능함


create nonclustered index idx_cust_N

on cust_N (customerid) include (추가컬럼)


15. 채우기비율 설정


   -채우기비율(FillFactor) : Index Leaf Page에만 영향

   -인덱스패딩(PAD_INDEX)  : ON 하면 Leaf외에도 채우기비율 적용



### Cover Index

-- Index Lookup --


if OBJECT_ID('Orders') is not null

drop table Orders

go


select * into Orders from Northwind.dbo.Orders

go


select * from Orders


Exec sp_helpindex Orders

create nonclustered index idx_ord_01 

on Orders(CustomerID) -- nchar(5)

go


set statistics profile on

set statistics io on

set statistics time on


select * from Orders

go


-- Index를 타고 있는가? --

select * 

from Orders

where CustomerID = 'ERNSH'

and ShipVia = 3

go


-- Index 강제 적용 --

select ShipVia 

from Orders with(index(idx_ord_01))

where CustomerID = 'ERNSH'

and ShipVia = 3

go


exec sp_helpindex orders


-- NC Index 재생성 -- (인덱스 포괄열 포함)

drop index Orders.idx_ord_01

create nonclustered index idx_ord_01 

on Orders(CustomerID) include (ShipVia)

go


-- NC Index 추가 생성 --

drop index Orders.idx_ord_02

create nonclustered index idx_ord_02 

on Orders(EmployeeID,ShippedDate)

go

Exec sp_helpindex Orders

go

-- 검색 --

Select * from Orders

where EmployeeID = 4

and ShippedDate >= CONVERT(datetime,'19960101',112)

and ShippedDate < CONVERT(datetime,'19980101',112)

go

-- Hint 사용 --

Select * from Orders with(index(idx_ord_02))

where EmployeeID = 4

and ShippedDate >= CONVERT(datetime,'19960101',112)

and ShippedDate < CONVERT(datetime,'19980101',112)

go


-- NC Index 제거 및 CI 추가 생성 --

drop index Orders.idx_ord_02

create clustered index idx_ord_03 

on Orders(EmployeeID,ShippedDate)

go

Exec sp_helpindex Orders

go

-- CI를 통한 검색 --

Select * from Orders

where EmployeeID = 4

and ShippedDate >= CONVERT(datetime,'19960101',112)

and ShippedDate < CONVERT(datetime,'19980101',112)

go


--별도] NC Index 강제 적용: Key Lookup을 하고 있는가? --

select * 

from Orders with(index(idx_ord_01))

where CustomerID = 'ERNSH'

and ShipVia = 3

go

-- 페이지 I/O 2개 <-- 논리적 읽기 수 2로 알수 있음

Select COUNT(*)

from Orders 

where CustomerID like 'Bo%'

go


-- Key Lookup의 횟수는 총 34회

-- 페이지 I/O가 2개 이므로, (81-2)

-- Key Lookup이 읽었던 페이지 수는 79페이지

Select CustomerID,ShippedDate,Freight

from Orders with(index(idx_ord_01))

where CustomerID like 'Bo%'

go


--> Heap의 상태에서 RID Lookup을 통한

--> 페이지 읽기의 수보다는 늘어난 상태

-- NCI 제거 후, 커버된 Index 생성 --

drop index Orders.idx_ord_01

go

create index idx_ord_04 on Orders (CustomerID)

include (ShipVia,Freight)

go


-- NCI 검색 : 읽기 페이지수 2개 --

Select CustomerID,ShippedDate,Freight

from Orders with(index(idx_ord_04))

where CustomerID like 'Bo%'

go

--> NCI Leaf레벨의 Index 페이지에 

--> ShippedDate,Freight 가 포함되어

--> Key Lookup 이 일어나지 않음




### INDEX Tuning

-- create database inDB


use inDB


select ProductID, Name, Color, Size, Weight

 into pTbl from Adventureworks.Production.Product


select SalesOrderDetailID as OrderID, ProductID, OrderQty,

unitPrice, LineTotal as Total

 into oTbl from Adventureworks.Sales.SalesOrderDetail


-- Create Constraint


Alter Table pTbl

 add constraint pk_pTbl Primary key (ProductID)


Alter Table oTbl

 add constraint pk_oTbl Primary key (OrderID)


Alter Table oTbl

 add constraint fk_pTbl 

foreign key (ProductID) references pTbl(ProductID)


--

select count(*) from pTbl

select count(*) from oTbl


-- 

Select Top(5)* from pTbl 

Select Top(5)* from oTbl


Select * from pTbl --> 7 페이지

Select * from oTbl --> 664 페이지


set statistics IO on

-- Tunning Advisor --

select p.ProductID, p.name, 

sum(o.orderqty) as [oTotal],sum(o.Total) as [Total]

from pTbl P inner join oTbl O on p.ProductID = o.ProductID

group by p.ProductID, p.name

having p.ProductID = '717';


select * from pTbl where color='Silver' order by name;


select ProductID, Total from oTbl order by Total Desc;


## 데이터 베이스 엔진 튜닝 관리자 실행 후 사용될 쿼리문 수행



### Nested Loop Join
set statistics profile on
-- [Nested Loop JOIN ]
select name,addr,mobile1,mobile2
from userTbl u, buyTbl b
where u.userID = b.userid
and prodName = '모니터'

select prodName,price,amount
from userTbl u, buyTbl b
where u.userID = b.userid
and name = '박주영'

-- [LOOP JOIN : 중첩루프조인]

SELECT * 
FROM Sales.Customer AS c
INNER JOIN Sales.CustomerAddress AS ca
ON c.CustomerID = ca.CustomerID
OPTION (LOOP join);
go

-- [Merge Join: 병합조인]

SELECT * 
FROM Sales.Customer AS c
INNER JOIN Sales.CustomerAddress AS ca
ON c.CustomerID = ca.CustomerID
OPTION (MERGE join, FORCE ORDER);
GO

SELECT * 
FROM Sales.Customer AS c
INNER JOIN Sales.CustomerAddress AS ca
ON c.CustomerID = ca.CustomerID
OPTION (MERGE join);
GO  

SELECT * 
FROM Sales.CustomerAddress AS ca
INNER JOIN Sales.Customer AS c
ON c.CustomerID = ca.CustomerID
OPTION (MERGE join);
GO

-- [Hash Join] --

SELECT * 
FROM Sales.Customer AS c
INNER JOIN Sales.CustomerAddress AS ca
ON c.CustomerID = ca.CustomerID
OPTION (hash join, FORCE ORDER);
GO

SELECT * 
FROM Sales.Customer AS c
INNER JOIN Sales.CustomerAddress AS ca
ON c.CustomerID = ca.CustomerID
OPTION (hash join);
GO



### Hash Match Join
-- Hash Match(Aggregate)
-- Stream Aggregate 

USE indb
GO

IF OBJECT_ID('TEST','U') IS NOT NULL
       DROP TABLE TEST
GO

CREATE TABLE TEST( A INT NOT NULL, B INT NOT NULL)
GO
-- NCI 생성

CREATE INDEX NC_TEST_A ON TEST(A)
GO

SET NOCOUNT ON
GO

DECLARE @I INT = 1
WHILE(@I <= 10000)
BEGIN
       INSERT INTO TEST SELECT @I, CONVERT(INT,RAND()* 1000) +1
       SET @I = @I + 1
END

SET NOCOUNT OFF
GO

SELECT  B
FROM TEST
GROUP BY B

SELECT A
FROM TEST
GROUP BY A

-- 기존 Index 삭제 후, Unique & NCI 생성

DROP INDEX TEST.NC_TEST_A
GO

CREATE UNIQUE INDEX NC_TEST_A ON TEST(A)
GO

SELECT A
FROM TEST
GROUP BY A

---------------------------------------------
-- Table 삭제 후, 재생성

IF OBJECT_ID('TEST','U') IS NOT NULL
     DROP TABLE TEST
GO

CREATE TABLE TEST( A INT NOT NULL, B INT NOT NULL)
GO

SET NOCOUNTON
GO

DECLARE @I INT = 1
WHILE(@I <= 2519)
BEGIN
       INSERT INTO TEST SELECT @I, @i
       SET @I = @I + 1
END

SET NOCOUNTOFF
GO

SELECT B
FROM TEST
GROUP BY B


### SQL Profiler 테스트

select * from Cust_A
select * from Cust_c
select * from Cust_n
go

select * from Cust_A
go
select * from Cust_c
go
select * from Cust_n
go

select * from Cust_A;
select * from Cust_c;
select * from Cust_n;
go



Posted by redkite
, |


 ### 트리거 (Trigger)


 1) 목적 : 데이터 무결성과 일관성 유지

 

 2) 종류:

- DML 트리거 : insert, update, delete

- DDL 트리거 : create, alter, drop


 3) 옵션:

- After : 실행 후(트랜잭션 로그가 계속 남음)

- Instead of : 실행 전(트랜잭션 로그가 안남음)


 4) 참고: 가상 테이블 (inserted, deleted)



use sqldb

create Table TA

 ( id int identity Primary key,

name char(8))


create Table TB

 ( id int identity Primary key,

name char(8))


insert into TA values ('jhAn')

insert into TB values ('jhAn')


select * from TA

select * from TB


create Trigger Trg_A on TA

 instead of insert

 as

rollback

go


create Trigger Trg_B on TB

 after insert

 as

rollback

go


drop Trigger Trg_A

drop Trigger Trg_B


Instead Vs. After 차이점




## Procedure Compile

drop Table spTable


select * into spTable 

from AdventureWorks.Sales.Customer

order by rowguid


select * from spTable


create index idx_spTbl on spTable (customerid)

Exec sp_helpindex spTable


--set statistics time off

set statistics IO on


select * from spTable where customerID < 10

select * from spTable where customerID < 1000


create Proc usp_1

@id int

as

select * from spTable where customerID < @id



Exec usp_1 10 --with recompile


Exec usp_1 1000 --with recompile


DBCC Freeproccache


alter Proc usp_1

@id int

with recompile

as

select * from spTable where customerID < @id



## 데이터 형식 우선순위 ##


1.     사용자 정의 데이터 형식(가장 높음)

2.     sql_variant

3.     xml

4.     datetimeoffset

5.     datetime2

6.     datetime

7.     smalldatetime

8.     date

9.     time

10.   float

11. real

12.   decimal

13.   money

14.   smallmoney

15.   bigint

16.   int

17.   smallint

18.   tinyint

19.   bit

20.   ntext

21.   text

22.   image

23.   timestamp

24.   uniqueidentifier

25.   nvarchar(nvarchar(max) 포함)

26.   nchar

27.   varchar(varchar(max) 포함)

28.   char

29.   varbinary(varbinary(max) 포함)

30.   binary(가장 낮음)


### 인덱스 생성 테스트 ###
use AdventureWorks
select * from AdventureWorks.sales.customer

create database indb

use indb
select * into Cust_A from AdventureWorks.sales.customer
select * into Cust_c from AdventureWorks.sales.customer
select * into Cust_n from AdventureWorks.sales.customer

select Top(5)* from Cust_A
select Top(5)* from Cust_C
select Top(5)* from Cust_N

Exec sp_helpindex cust_A
Exec sp_helpindex cust_C
Exec sp_helpindex cust_N

create Clustered index idx_cust_C
on cust_C (customerid)

create nonclustered index idx_cust_N
on cust_N (customerid)

set statistics io on
set statistics time on

select * from Cust_A where customerID < 1000
select * from Cust_C where customerID < 1000
select * from Cust_N where customerID < 1000


select * from Cust_A where customerID < 1000
select * from Cust_C where customerID < 1000
select * from Cust_N with(index(idx_Cust_N)) 
where customerID < 1000



### 형 변환 ##

use indb
go

select * from master.dbo.syscolumns
select * from tempdb.dbo.syscolumns
select * from model.dbo.syscolumns
select * from msdb.dbo.syscolumns

if OBJECT_ID('t_columns') is not null
drop table t_columns
go

select t.*
into t_columns
from 
(select CAST(1 as smallint)as dbid,* from master.dbo.syscolumns
union all
select CAST(2 as smallint)as dbid,* from tempdb.dbo.syscolumns
union all
select CAST(3 as smallint)as dbid,* from model.dbo.syscolumns
union all
select CAST(4 as smallint)as dbid,* from msdb.dbo.syscolumns
) t
go

select * from t_columns
go
select COUNT(*) as cnt from t_columns
go

create index idx_t_01 on t_columns (dbid,name)
go

Exec sp_helpindex t_columns

-----------------------------------------------
set statistics profile on
set statistics io on
set statistics time on
go

select * 
from t_columns 
-- Index Scan --
select * 
from t_columns 
where name = 'addr'

-- Index Seek --
select * 
from t_columns 
where name = 'addr'
and dbid in (1,2,3,4)
-- Index 제거 --

sp_helpindex t_columns

drop index t_columns.idx_t_01
go
-- index 추가 --
create index idx_t_02 on t_columns(name)
go

-- column 추가
select * from t_columns
go

alter table t_columns -- 자동증가값
add no_tmp int identity not null
go

alter table t_columns -- null 값
add no varchar(10)
go

-- 값 변경 null --> 자동증가값
update t_columns
set no = no_tmp
go

-- Index 추가
create index idx_t_03 on t_columns (no)
go

select * from t_columns
where name = 'rowsetid'

---------------------------------------
-- Explicit 형 변환 --
select * from t_columns
where SUBSTRING(name,1,8) = 'rowsetid'
go

select * from t_columns
where name like 'rowsetid'
go

-- Implicit 형변환 --
select * from t_columns
where no=1 --varchar(10)
go       
--> 데이터 우선순위 (Int > varchar) 
--> 변환 (varchar --> Int)
select * from t_columns
where no = CONVERT(varchar(10),1)
go
--> 암시적 변환 예
--> 날짜 char(8)
--> where 계약일자 = 20130311
--> 데이터 우선순위 (Int > char(8)) 
--> 변환 (char(8) --> Int)



### 인덱스 기본키 생성
use xDB
go

create table T1 (
a int,
b int,
c int)
go

Exec sp_help T1
Exec sp_helpindex T1
go

create table T2 (
a int Primary key,
b int,
c int)
go

Exec sp_help T2
Exec sp_helpindex T2
go

create table T3 (
a int Primary key,
b int Unique,
c int Unique)
go

Exec sp_helpindex T3
go

create table T4(
a int Primary key nonclustered,
b int Unique clustered,
c int Unique)
go

Exec sp_helpindex T4
go

create table T5(
a int Primary key nonclustered,
b int Unique clustered,
c int Unique clustered) --< 불가능
go

Exec sp_helpindex T5
go

create table T6(
a int Primary key nonclustered,
b int Unique nonclustered,
c int Unique nonclustered)
go

Exec sp_helpindex T6
go

## 인덱스 생성

exec sp_helpdb indb
go

if OBJECT_ID('empTbl') is not null
drop table empTbl
go

use inDB
create table empTbl(
empID int not null,
LastName nvarchar(20) null,
FirstName nvarchar(10) null,
HireDate datetime null
)

insert into empTbl
select EmployeeID, LastName, FirstName, HireDate
from Northwind.dbo.Employees
order by EmployeeID
go

select * from empTbl
go

-- Table에 Index 확인 --
Exec sp_helpindex empTbl
go

-- Index 생성 --> LastName
create index idx_empTbl_LastName on empTbl(LastName)
with (fillfactor = 1, pad_index = on)
go

-- index 아이디 확인 --
select index_id, name
from sys.indexes 
where object_id = object_id('empTbl')
go

-- ind ('Database 명','Table 명','Index 아이디')
--> Page Type : DataPage(1),IndexPage(2),IAM(10)
--> Index Level : 루트(2),브랜치(1),리프(0)
dbcc ind('inDB','empTbl',2)
go

-- dbcc page 앞에 실행해야 함
--> dbcc 명령들은 기본적으로 출력을 로그에만 남김
dbcc traceon(3604)
go
-- page('Database 명','파일번호','페이지번호','출력옵션[0~3]')
dbcc page('indb',1,118,3)
go

------- Index 생성 기초 ------------------
-----------------------------------------
-- Clustered Index 생성 --

Exec sp_helpindex empTbl
SP_SPACEUSED [empTbl] 
GO

alter table empTbl 
add constraint idx_emp_pk
primary key clustered (empID)
go

alter table empTbl
drop constraint idx_emp_pk
go


### 인덱스 정보 확인 ###
USE ADVENTUREWORKS
GO
SP_HELP [PERSON.ADDRESS] 
GO
SP_HELPINDEX [PERSON.ADDRESS] 
GO
USE ADVENTUREWORKS
GO
SELECT * FROM SYS.INDEXES 
WHERE OBJECT_ID = OBJECT_ID('PERSON.ADDRESS')
GO
SELECT * FROM SYS.INDEX_COLUMNS 
WHERE OBJECT_ID = OBJECT_ID('PERSON.ADDRESS')
GO
USE ADVENTUREWORKS
GO
SELECT * FROM SYS.DM_DB_INDEX_PHYSICAL_STATS 
(DB_ID(N'ADVENTUREWORKS'), OBJECT_ID(N'PERSON.ADDRESS'),
NULL, NULL , 'DETAILED')
GO
SELECT * FROM SYS.DM_DB_INDEX_OPERATIONAL_STATS 
(DB_ID(N'ADVENTUREWORKS'), OBJECT_ID(N'PERSON.ADDRESS'), NULL,
NULL)
GO
SELECT * FROM SYS.DM_DB_INDEX_USAGE_STATS 
WHERE OBJECT_ID = OBJECT_ID(N'PERSON.ADDRESS')
GO
SELECT INDEXPROPERTY(OBJECT_ID('PERSON.ADDRESS'), 
'PK_Address_AddressID','IsClustered')AS [Is Clustered],
INDEXPROPERTY(OBJECT_ID('PERSON.ADDRESS'),
'PK_Address_AddressID','IndexDepth') AS [Index Depth],
INDEXPROPERTY(OBJECT_ID('PERSON.ADDRESS'),
'PK_Address_AddressID','IndexFillFactor') AS [Fill Factor];
GO



### 인덱스 활용
USE ADVENTUREWORKS
GO

Exec sp_helpindex [SALES.SALESORDERDETAIL]
select * from SALES.SALESORDERDETAIL

drop index SALES_QTY_IDX on SALES.SALESORDERDETAIL
GO

set statistics io on

SELECT * FROM SALES.SALESORDERDETAIL 
WHERE ORDERQTY >= 35
GO

Exec sp_helpindex [SALES.SALESORDERDETAIL]

CREATE INDEX SALES_QTY_IDX ON SALES.SALESORDERDETAIL(ORDERQTY) 
GO

SELECT * FROM SALES.SALESORDERDETAIL 
WHERE ORDERQTY >= 35
GO
SELECT * FROM SALES.SALESORDERDETAIL
WHERE ORDERQTY - 5 >= 30
GO
USE ADVENTUREWORKS
GO
SP_HELPINDEX [PRODUCTION.PRODUCT] 
GO
SELECT NAME FROM PRODUCTION.PRODUCT 
WHERE NAME LIKE '%Blade%'
GO
SELECT NAME FROM PRODUCTION.PRODUCT
WHERE NAME LIKE 'Blade%'
GO



### 인덱스 비활성화
USE ADVENTUREWORKS
GO

select * from Person.Address

SP_HELPINDEX [PERSON.ADDRESS] 
GO
SP_SPACEUSED [PERSON.ADDRESS] 
GO

set statistics io on

select * from Person.Address
where StateProvinceID < 3

ALTER INDEX IX_ADDRESS_STATEPROVINCEID ON PERSON.ADDRESS 
rebuild -- 활성화
DISABLE  -- 비활성화
GO
SP_HELPINDEX [PERSON.ADDRESS] 
GO
SP_SPACEUSED [PERSON.ADDRESS]
GO
ALTER INDEX PK_Address_AddressID ON PERSON.ADDRESS 
DISABLE
GO
SP_SPACEUSED [PERSON.ADDRESS]
GO
ALTER INDEX IX_ADDRESS_STATEPROVINCEID ON PERSON.ADDRESS 
REBUILD WITH (ONLINE=ON)
GO
ALTER INDEX ALL ON PERSON.ADDRESS REBUILD 
GO
SP_SPACEUSED [PERSON.ADDRESS]
GO
ALTER INDEX IX_ADDRESS_STATEPROVINCEID ON PERSON.ADDRESS 
DISABLE
GO
SELECT IS_DISABLED FROM SYS.INDEXES
WHERE OBJECT_ID = OBJECT_ID('PERSON.ADDRESS')
AND NAME = 'IX_ADDRESS_STATEPROVINCEID'
GO
ALTER INDEX IX_ADDRESS_STATEPROVINCEID ON PERSON.ADDRESS
REBUILD WITH (ONLINE=ON)
-- ONLINE=ON (온라인 상태, 즉 Table Lock을 안 걸고 실행)
GO

Posted by redkite
, |


Script.zip


오라클 데이터베이스를 생성할 때 보통은 DBCA를 이용한다.
그러나 DBCA만 사용해 DB를 생성하다보면, DBCA를 사용할 수 없는 상황에는 당황하게 된다.


다음은 DBCA를 이용할 수 없는 경우 오라클 데이터베이스를 생성하는 절차다.

  1. SID, ORACLE_HOME 설정

    export ORACLE_SID=testdbexport ORACLE_HOME=/path/to/oracle/home

  2. 초기화 파라미터 파일 생성 (minimal)
    $ORACLE_HOME/dbs에 init<SID>.ora 파일을 만든다.

    control_files = (/path/to/control1.ctl,/path/to/control2.ctl,/path/to/control3.ctl)
    undo_management = AUTO
    undo_tablespace = UNDOTBS1
    db_name = test
    db_block_size = 8192
    sga_max_size = 1073741824 # 1GBsga_target = 1073741824 # 1GB

  3. 패스워드 파일 생성

    $ORACLE_HOME/bin/orapwd file=$ORACLE_HOME/dbs/pwd{sid}.ora password=oracle entries=5

  4. 인스턴스 기동

    $ sqlplus '/as sysdba'

    SQL> startup nomount

  5. CREATE DATABASE 문 실행

    create database test
    dblogfile group 1 ('/path/to/redo1.log') size 100M,
    group 2 ('/path/to/redo2.log') size 100M,
    group 3 ('/path/to/redo3.log') size 100M
    character set ko16ksc5601
    national character set al16utf16
    datafile '/path/to/system.dbf' size 500M autoextend on next 10M maxsize unlimited extent management local
    sysaux datafile '/path/to/sysaux.dbf' size 100M autoextend on next 10M maxsize unlimited
    undo tablespace undotbs1 datafile '/path/to/undotbs1.dbf' size 100M
    default temporary tablespace temp tempfile '/path/to/temp01.dbf' size 100M;

    CREATE DATABASE 문 Syntax는 다음과 같다.
    CREATE DATABASE [database name]
    [CONTROLFILE REUSE]
    [LOGFILE [GROUP integer] file specification]
    [MAXLOGFILES integer]
    [MAXLOGMEMBERS integer]
    [MAXLOGHISTORY integer]
    [MAXDATAFILES integer]
    [MAXINSTANCES integer]
    [ARCHIVELOG|NOARCHIVELOG]
    [CHARACTER SET charset]
    [NATIONAL CHARACTER SET charset]
    [DATAFILE filespec [autoextend]]
    [DEFAULT TEMPORARY TABLESPACE tablespace filespec]
    [UNDO TABLESPACE tablespace DATAFILE filespec]
    [SET TIME_ZONE [time_zone_region]];

  6. Data Dictionary View 생성 스크립트 실행

    $ORACLE_HOME/rdbms/admin/CATALOG.sql$ORACLE_HOME/rdbms/admin/CATPROC.sql

  7. SPFILE 생성

    SQL> create spfile from pfile;

  8. 추가 테이블스페이스 생성
  9. sys, system 계정 암호 변경

Posted by redkite
, |

트랜잭션이란? 


데이터베이스의 논리적인 작업의 처리 단위이다.

여기서 작업이라 함은 일반적으로 데이터베이스에서의 데이터 입력,수정,

삭제 등을 말하는 것으로 데이터베이스에 변경사항을 유빌하는 행위를 말한다.

그리고 하나의 입력, 수정, 삭제 직업이 개별적인 트랜잭션으로 처리될 수도 있지만,

하나의 트랜잭션 내에서 여러 작업이 포함될 수도 있다.

그래서 트랜잭션읕 물리적이 아닌 논리적인 작업의 처리단위라고 하는 것이다.

그리고 트랜잭션의 기본 개념은 All or Nothing 이다.



 # 트랜잭션


-- 명시적 트랜잭션   : Begin(O),Commit(O)

-- 암시적 트랜잭션   : Begin(X),commit(O) ==> 오라클

-- 자동커밋 트랜잭션 : Begin(X),commit(X) ==> MS SQL Server



-- set implicit_transactions on


-- AA 창 --

select * from TC


begin tran

 update TC set id = 11 where id = 10

 update TC set id = 22 where id = 20

 update TC set id = 33 where id = 30

commit tran


select @@TRANCOUNT


-- BB 창 --

 use master

 Alter database sqlDB set allow_snapshot_isolation on

 set Transaction isolation level snapshot

  -- 잠금에 걸린 Tabble이라도 메모리(캐시)가 아닌 

-- 데이터 파일의 내용을 무조건 읽어올수 있도록 만들어 줌

select * from TC



# 체크포인트


체크 포인트(Check Point) 프로세스는 현재까지 메모리에서 진행된 모든 내용을 데이터 파 일과 로그 파일에 기록하는 프로세스로이다. 마치 워드나 엑셀 같은 프로그램에서 저장버튼 을 누르는 것과 같은 역할을 수행한다. 미러한 체크 포인트는 기본적으로 SQL Server가 1분마다 상황을 체크해서 많은 작업(많은 작업에 대한 판단은 SQL Server가 한다)이 있었던 경우 발생하기 때문에 궁극적으로 비주 기적으로 발생된다고 할 수 있다. 다시 말해서 데이터베이스에서 많은 작업이 일어나면 체 크 포인트가 발생하는 주기는 1분이 될 것이며, 데이터베이스에서 일어나는 작업이 많지 않 으면 체크 포인트가 발생하는 주기를 예측할 수 없다는 말이 된다.


# 레이지 라이터 & 로그라이터


 - 레이지 라이터(Lazy Writer)

레이지 라이터(Lazy Writer)라는 프로세스는 메모리 상의 프로시저 캐시에서 시용 빈도가

낮은 실행 계획을 메모리에서 제거하고 버퍼 캐시에 있는 더티 페이지(Dirty Page)들을 디

스크에 기록함으로써 메모리상에 빈 공간을 확보하기 위해서 동작하며, 이 역시 백그라운드

프로세 스로 주기적으로 동작한다.


 - 로그 라이터(Log Writer)라는 프로세스는 트랜잭션이 완료(Commit, 커밋)되면 자동으로

커밋된 트랜잭션에 대한 로그를 트랜잭션 로그 파일에 기록하는 프로세스이다.




### 참조 제약 조건

create table byTbl

(no <-- 숫자 증가값

 name --> uTbl(userid)

 prodname

 groupname

 price

 amount

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

  create Table byTbl

(num int Identity Not Null Primary Key,

 userid nchar(8) Not Null 

Foreign Key References uTbl(userid),

 prodName nchar(6) Not Null,

 groupName nchar(4),

 price int Not Null,

 amount smallint Not Null

)

go



### JOIN 사용

-- userTbl,buyTbl에서 하세요


--1) 키가 180 이상인 사람의 userid, 이름, 거주지는?

select userID, name, addr

from userTbl

where height >= 180


--2) 핸드폰 번호가 011,018 인 사람의 userid, 이름, 거주지는?

select userID,name,addr,mobile1

from userTbl

where mobile1 in ('011','018')


--3) 이름이 박주영인 사람의 구매한 목록, 즉

-- 이름,userid, 상품명, 가격, 수량을 구하시요.

select u.name, u.userID, b.prodName, b.price, b.amount

from userTbl u, buyTbl b

where u.userID = b.userid

  and u.name = '박주영'

  

SELECT     userTbl.userID, userTbl.name, buyTbl.prodName, buyTbl.price, buyTbl.amount

FROM         buyTbl INNER JOIN

             userTbl ON buyTbl.userid = userTbl.userID

WHERE     (userTbl.name = N'박주영')


--4) 키가 182 이상인 사람들의 이름,키,userid, 

-- 상품명,가격,수량은?


select u.name, u.height, u.userID, b.prodName, b.price, b.amount

from userTbl u, buyTbl b

where u.userID = b.userid

and u.height >= 182


--5) 키가 182 이상인 사람별 이름, 총구매금액 중 1000이상인

-- 것만 나타내시오

select u.name, sum(b.price*b.amount) as 총구매금액

from userTbl u, buyTbl b

where u.userID = b.userid

and u.height >= 182

group by u.name

having sum(b.price*b.amount) >= 1000


--6) 안정환보다 키가 큰 사람의 이름,birthyear,addr,height ?

--1> 안정환의 키?

select height

from userTbl

where name = '안정환' --> 182

--2> 그 키보다 큰사람의 ~~~~

select name,birthYear,addr,height

from userTbl

where height > 182

--3> 문장 합치기

select name,birthYear,addr,height

from userTbl

where height > (select height

from userTbl

where name = '안정환')

--7) 김남일보다 키가 큰 사람의 이름과 거주지,키

--   구매상품명,가격,수량은?

--1> 김남일의 키는?

select height

from userTbl

where name = '김남일' -- 183

--2> 그 키보다 큰 사람의 ~~~?

select u.name,u.addr,u.height,b.prodName,b.price,b.amount

from userTbl u, buyTbl b

where u.userID = b.userid

and u.height > 183

--3> 문장합치기

select u.name,u.addr,u.height,b.prodName,b.price,b.amount

from userTbl u, buyTbl b

where u.userID = b.userid

and u.height > (select height

from userTbl

where name = '김남일')




### VIEW 설명


 # 뷰(View)


 1) 정의 : Select 문장의 덩어리 

(가상의 논리적 테이블)


 2) 목적 : 편의성, 보안성, 성능향상


 3) 종류 :

- 일반 View

- Index View

- Partition View



drop view v_userTbl


create view v_userTbl

as

 select userid,name,addr from userTbl


select * from v_userTbl 

where name='이천수'


select * from userTbl


update v_userTbl set addr='ZZ' where name = '이천수'

update v_userTbl set height=100 where name = '이천수'


insert into v_userTbl values ('KKK','김금갑','PP')

insert into v_userTbl (userid,name,addr) 

values ('KKK','kkKim','PP')


create View v_userTbl3

 as

 select userid,name,birthyear,addr from userTbl


insert into v_userTbl3 values ('KKK','kkKim','1977','PP')

select * from v_userTbl3


delete v_userTbl3 where userid='KKK'


select * from userTbl


create View v_userTbl4

 as

 select * from userTbl where height >= 180


select * from v_userTbl4


delete v_userTbl4 where height < 180 

select * from userTbl


update v_userTbl4 set birthyear ='1111' 

where height < 180


insert into v_userTbl4 

values ('TTT','ggHong','4444','GG',010,0101,190)

insert into v_userTbl4 

values ('ZZZ','ggHong','4444','GG',010,0101,100)


select * from userTbl


alter view v_userTbl4

as

 select * from userTbl where height >= 180

 with check option



select * from sys.views


Exec sp_helptext 'v_userTbl4'


alter View v_userTbl4

 with Encryption

as

 select * from userTbl where height >= 180

with check option


use sqldb


select * from userTbl --> userTbl2


select * into userTbl2 from userTbl



select * from userTbl2


-- view를 생성 

-- (userid, name, birthyear, addr, height)


create view v_uTbl2

as

select userid,name,birthyear,addr,height

from userTbl2


select * from v_uTbl2


-- userTbl2 에서 height 컬럼을 제거해보세요

alter table usertbl2

drop column height

go


select * from userTbl2


select * from v_uTbl2 <-- 실행되는지요?


drop view v_uTbl3


create view v_uTbl3

with schemabinding

as

select userid,name,birthyear,addr,mobile2

from dbo.userTbl2 --> table명 앞에 dbo 스키마를 선언

go


select * from v_uTbl3


alter table usertbl2

drop column mobile2

go



## SQL Injection


 ID     [  admin' or 1=1 !--  ] 

 PWD    [  1234  ]  


select * from where id ='swhong' or 1=1 



   select * from where id='admin' or 1=1 1!--' and pwd = '1234'


  Exec sp_userid('jane','1234')


 ### 저장프로시저 (Stored Procedure)


 1) 정의 : - Transact-SQL 문장의 집합 


 2) 용도 :

- 어떠한 동작을 절차적 일괄처리 작업하는데 사용

- SQL Server에서 사용하는 프로그래밍 기능


 3) 특징 :

- SQL Server의 성능향상 (첫 실행시 컴파일, 재컴파일 안함)

- 모듈식 프로그래밍 가능

- 보안강화 (저장프로시저 마다의 권한할당 가능)

- 네트워크 전송량 감소 (긴 쿼리문장의 단순화)


 4) 장점 :

- 빠르다

- 파라미터를 사용할 수 있다

- 여러 어플리케이션과 공유할수 있다


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

 # 일반적인 T SQL 구문 실행절차

1. 첫실행시

 1) 구문분석

 2) 개체검사

 3) 권한확인

 4) 최적화경로확인

 5) 컴파일(with 실행계획) --> 메모리 상주

 6) 실행

2. 두번째실행시 (구문이 같아야)

 1) 기 컴파일 사용

 2) 실행


 # 저장 프로시저

1. 첫실행시

 1) 구문분석

 2) 개체검사

 3) 권한확인

 4) 최적화경로확인

 5) 컴파일(with 실행계획) --> 메모리 상주

 6) 실행

2. 두번째실행시 (구문이 같지않아도)

 1) 기 컴파일 사용

 2) 실행


 use sqldb


create Procedure usp_userTbl

as

 select * from userTbl


Exec usp_userTbl


-- View 일 경우 --

create view v_Test 

as

   select * from userTbl

   

select * from v_Test where userID = 'AJH'


create Proc usp_userTbl2

 @userid nchar(8)

as

 select * from userTbl where userid = @userid

go


Exec usp_userTbl2 'AJH'


create Proc usp_userTbl3

 @a int,

 @b int

as

 select * from userTbl where birthyear > @a and birthyear <= @b

go


Exec usp_userTbl3 1978,1982



create Proc usp_userTbl4

@userid nchar(8)

as

declare @byear int

select @byear = birthyear from userTbl where userid = @userid

if (@byear >= 1978)

Begin

Print 'Low Age'

end

else

Begin

Print 'High Age'

end

go


Exec usp_userTbl4 'AJH'


-- Input Value, Output Value

create Proc usp_userTbl5

@userid nchar(8),

@outAge int OutPut

as

Declare @bYear int

select @bYear = birthyear from userTbl where userid = @userid

select @outAge = Year(getdate()) - @bYear


-- Execute SP

declare @iAge int

Exec usp_userTbl5 'AJH', @iAge Output

Print 'Your Age ==> ' + cast(@iAge as char(5))


select @@NESTLEVEL





### 사용자 정의 함수 (User Defined Function)


 1) 정의 : 리턴값을 갖는 프로시저의 종류


 2) 유형 : 

- 스칼라(Scalar) 함수 

- 테이블 함수

  - 인라인 테이블 값 (Inline Table Valued)함수

  - 다중문 테이블 값 (Multi Statement Table Valued)함수


 3) 제약사항 :

- 함수 내부에 Try Catch 문을 사용할 수 없다

- 함수 내부에 DDL문(Create/Alter/Drop)을 사용할 수 없다


 @ 스칼라 함수: Return문에 의해서 하나의 단일값을 돌려주는 함수

 @ 인라인 테이블값 함수 : Select 문장의 결과 집합을 돌려주는 함수

 @ 다중문 테이블 값 함수 : 정의된 임시 테이블 자체를 돌려주는 함수




 create #tmpTbl (id txt) : 사용할 수 없음



Inline_Fuction.sql


Muti_Fuction.sql


Scalar_Fuction.sql



Posted by redkite
, |

exec sp_help usertbl  -- 테이블 분석

 




## 제약조건(Constraint)

create Table uTbl

(userID nchar(8) Not Null 

Constraint PK_userTbl_userID Primary Key,

 name nvarchar(10) Not Null

Constraint UQ_userTbl_name Unique,

 birthYear int Not Null --> 올해와 이후 100년 사이

Constraint CK_userTbl_BY 

check(birthyear>=year(getdate())

and birthyear<year(dateadd(yy,100,GETDATE()))),

 addr nchar(4) Not Null  --> 기본값 (서울)

Constraint DF_userTbl_addr default('서울'),

 mobile1 nchar(3) --> 010,011,016,017,018,019

Constraint CK_userTbl_mob1

check(mobile1 in ('010','011','016','017','018','019')),

 mobile2 nchar(8),

 height smallint --> 0 ~ 250

Constraint CK_userTbl_height

check (height > 0 and height <= 250)

)

go


select GETDATE()

select YEAR(getdate())

select year(dateadd(yy,100,GETDATE()))

 

 

 

 

SQL Server의 기본 데이터 저장 단위는 페이지입니다. 데이터베이스에서 데이터 파일(.mdf 또는 .ndf)에 할당되는 디스크 공간은 논리적인 페이지로 나뉘어지며 0에서 n 사이의 숫자가 연속으로 페이지에 매겨집니다. 디스크 I/O 작업은 페이지 수준에서 수행됩니다. 즉 SQL Server는 전체 데이터 페이지를 읽거나 씁니다.

익스텐트는 실제로 연속하는 8페이지를 모은 것으로 페이지를 효율적으로 관리하는 데 사용됩니다. 모든 페이지는 익스텐트로 저장됩니다.

SQL Server에서 페이지의 크기는 8KB입니다. 이 사실은 SQL Server 데이터베이스에 메가바이트당 128페이지가 있음을 의미합니다. 각 페이지는 96바이트 머리글로 시작하는데 이 머리글은 페이지에 대한 시스템 정보를 저장하는 데 사용됩니다. 페이지 번호, 페이지 유형, 해당 페이지의 사용 가능한 공간 크기 그리고 해당 페이지를 소유하고 있는 개체의 할당 단위 ID와 같은 정보를 저장합니다.

다음 표에서는 SQL Server 데이터베이스의 데이터 파일에서 사용되는 페이지 유형을 보여 줍니다.

페이지 유형

내용

데이터

text in row가 ON으로 설정된 경우에 text, ntext, image, nvarchar(max), varchar(max), varbinary(max)xml 데이터를 제외한 모든 데이터가 있는 데이터 행

인덱스

인덱스 항목

텍스트/이미지

큰 개체 데이터 형식:

  • text, ntext, image, nvarchar(max), varchar(max), varbinary(max)xml 데이터

데이터 행이 8KB를 초과하는 경우 가변 길이 열:

  • varchar, nvarchar, varbinarysql_variant

전역 할당 맵, 공유 전역 할당 맵

익스텐트가 할당되었는지 여부에 대한 정보

페이지의 사용 가능한 공간

페이지 할당 및 페이지의 사용 가능한 공간에 대한 정보

인덱스 할당 맵

테이블 또는 인덱스에서 할당 단위당 사용하는 익스텐트에 대한 정보

대량 변경 맵

마지막 BACKUP LOG 문 이후에 할당 단위당 대량 작업에 의해 수정된 익스텐트에 대한 정보

차등 변경 맵

마지막 BACKUP DATABASE 문 이후에 할당 단위당 변경된 익스텐트에 대한 정보

참고참고

로그 파일은 페이지는 포함하지 않으며 일련의 로그 레코드를 포함합니다.

데이터 행은 머리글 바로 다음부터 시작하여 페이지에 차례로 나옵니다. 행 오프셋 테이블은 페이지 끝에서 시작하는데 각 행 오프셋 테이블에는 해당 페이지에 있는 각 행에 대한 항목이 하나씩 있습니다. 각 항목은 해당 행의 첫째 바이트가 페이지 시작 지점에서 얼마나 떨어져 있는지를 기록합니다. 행 오프셋 테이블의 항목 순서는 페이지의 행 순서의 역순입니다.

행 오프셋이 있는 SQL Server 데이터 페이지

대용량 행 지원

행들이 여러 페이지에 걸쳐 있을 수 없지만 그러한 행 부분들이 해당 행의 페이지를 벗어나서 해당 행이 실제로는 아주 커질 수 있습니다. 한 페이지의 단일 행에 데이터와 오버헤드가 최대 8,060바이트(8KB)까지 저장됩니다. 그러나 텍스트/이미지 페이지 유형에 저장되는 데이터는 여기에 포함되지 않습니다. varchar, nvarchar, varbinary 또는 sql_variant 열이 있는 테이블의 경우 이러한 제한이 완화됩니다. 테이블에 있는 모든 고정 및 변수 열의 전체 행 크기가 8,060바이트 한계를 초과하면 SQL Server는 하나 이상의 가변 길이 열을 가장 너비가 넓은 열부터 시작하여 ROW_OVERFLOW_DATA 할당 단위에 있는 페이지로 동적으로 옮깁니다. 삽입 또는 업데이트 작업으로 행의 전체 크기가 8060바이트 한계를 초과하면 이러한 작업이 수행됩니다. 열이 ROW_OVERFLOW_DATA 할당 단위의 페이지로 이동하면 IN_ROW_DATA 할당 단위에 있는 원래 페이지의 24바이트 포인터가 그대로 유지됩니다. 후속 작업으로 행 크기가 줄면 SQL Server가 동적으로 열을 다시 원래 데이터 페이지로 이동합니다. 자세한 내용은 8KB를 초과하는 행 오버플로 데이터를 참조하십시오.

익스텐트는 공간 관리의 기본 단위입니다. 하나의 익스텐트는 실제로 연속하는 8페이지 또는 64KB입니다. 이 사실은 SQL Server 데이터베이스에 메가바이트당 익스텐트가 16개 있음을 의미합니다.

SQL Server은 효율적인 공간 할당을 위해 적은 양의 데이터를 포함하는 테이블에 전체 익스텐트를 할당하지 않습니다. SQL Server에는 다음 두 가지 유형의 익스텐트가 있습니다.

  • 균일 익스텐트는 단일 개체가 소유합니다. 또한 익스텐트의 전체 8페이지는 소유하는 개체만 사용할 수 있습니다.

  • 혼합 익스텐트는 최대 8개의 개체가 공유할 수 있습니다. 익스텐트의 8페이지를 각각 다른 개체가 소유할 수 있습니다.

일반적으로 새 테이블이나 인덱스에는 혼합 익스텐트의 페이지가 할당됩니다. 테이블이나 인덱스의 페이지가 8페이지로 증가하면 후속 할당을 위해 균일 익스텐트를 사용하도록 전환됩니다. 인덱스에 8개의 페이지를 생성하는 데 충분한 행을 가진 기존 테이블에서 인덱스를 만드는 경우 인덱스에 대한 모든 할당 항목은 균일 익스텐트에 있습니다.

혼합 및 단일 익스텐트


 

 

### SHRINK 테스트

@@@ shrink database @@@

use master
create database shrinkDB
on Primary
(name = shrinkDB,
 Filename = N'C:\database\sDB\shrinkDb.mdf',
 size=3MB)
Log on
(name = shrinkDB_Log,
 Filename= N'C:\database\sDB\shrinkDb_log.ldf',
 size=3MB)

-- 1 (insert A) --

use shrinkDB
create Table test (txt varchar(1024))
go

Declare @i int
set @i = 0
while @i < 1024*10
Begin
 insert into test values (replicate ('A', 1024)) 
 set @i = @i+1
end

-- 2 (insert B,C) --

Declare @i int
set @i = 0
while @i < 1024*10
Begin
 insert into test values (replicate ('B', 1024)) 
 set @i = @i+1
end

set @i = 0
while @i < 1024*10
Begin
 insert into test values (replicate ('C', 1024)) 
 set @i = @i+1
end

-- 3 (shrink database [SSMS])

-- 4 (view Size)

-- 5 (delete B)
delete test where substring(txt,1,1) = 'B'

-- 6 (shrink database [SSMS])

-- 7 (view Size)



### File Group


 - Database Object에 대한 저장

 - Data File의 묶음

 - Raid 0 구성 (I/O를 향상) 

   -> 물리적 드라이브가 실제 분리되어 있어야 효과

 - 주 Data File(.mdf)은 기본적으로

   -> Primary File Group 소속되어져 있음

 - Primary File Group은 읽기 전용 그룹이 될 수 없음


 - 나머지 File Group은 읽기 전용 그룹이 될 수 있음


 - 백업/복원의 대상이 됨


 - 증분복원: 단계적 복원이 가능


 

Posted by redkite
, |

# Table 이란??

 - Data가 저장되어지는 논리적 구조의 객체(그릇)
 - 행(Record)과 열(Column)이 존재
 - Table in RDB(관계형DB)에서는 자기/다른 Table
 과의 관계(Relationship)설정이 가능

 -> 일관성, 무결성을 위한 모델링을 하게되면

    분리된 Table 사이에서 연결고리를

    찾는게 어려워 지기때문에

    그것을 관계를 통해 해결

 - 모델링, 정규화 --> 데이터의 무결성


 # E-R 관계 사상 알고리즘

 - 단계 1: 정규 엔티티  <= 테이블 + 기본키
 - 단계 2: 약한 엔티티  <= 부모의 키 + 부분키
 - 단계 3: 1:1 관계타입  <= 부모의 PK -> 자식의 PK,FK
 - 단계 4: 1:N 관계타입  <= 부모의 PK -> 자식의 FK
 - 단계 5: M:N 관계타입  <= 신규테이블 + [양측의 PK -> FK]
 - 단계 6: 다치 애트리뷰트  <= 신규테이블 + [부모의 PK -> FK]

 

 

# 정규화란 중복성을 최소화하고 정보의 일관성을 보장하기 위한 관계형 데이터 베이스에서 제일 중요한 개념.


# 정규화를 하는 이유

 - 데이터의 중복성 제거
 - 데이터 모형의 단순화
 - Entity,Attribut의 누락여부
 - 데이터모형의 안전성 검증

 

 

 

 # Data 무결성

 1) 참조무결성 : 테이블간 불일치 데이터 방지하자
 2) 실체무결성 : 기본키로 Row를 구분하자
 3) 도메인무결성: 잘못된 형식을 방지하자

 # 정규화
 
 1) 1정규형
 - 데이터의 중복제거
 - 컬럼의 중복제거

 2) 2정규형
 - 기본키 전체에 의존 컬럼분류

 3) 3정규형
 - 일반컬럼 의존적 컬럼 분리


 

# 제 1정규화

 - 엔티티 내의 모든 속성은 반드시 하나의 값을 가져야 한다.

 - 여러 값을 가진 컬럼이 존재할 수 없다. 즉 반복되는 그룹이 존재해서는 안 된다. 각 행과 열에는 하나의 값만이 올수 있다.

# 제 2정규화

 - 복합키를 식별자로 가지는 경우 복합키의 일부분에만 종속적인 항목을 분류하는 작업

 - 모든키가 아닌 컬럼은 기본 키 전체에 의존적이여야 한다. 기본키의 일부분에 의존적이어서는 안 된다.

# 제3정규화
 
 - 엔티티 내의 식별자를 제외한 모든 속성은 종속될 수 없다.

 - 키가아닌 컬럼은, 다른 키가 아닌 컬럼에 의존적일어서는 안된다.

# 역정규화

 - 데이터의 중복을 통해 과도한 논리적 결합현상을 피한다.
 
 - 유도된 컬럼을 추가하여 불필요한 연산을 피한다. (예)판매금액=수량*단가

 - 하나의 테이블을 2개 이상의 테이블로 분리하여 불필요한 컬럼의 검색을 피한다.

 - 자주 사용되는 테이블의 논리적 결합을 피하기 위해 집계테이블을 생성한다.

논리적 모델링 단계에서 논해야 하는 문제는 개념적 모델링 후,

매핑룰에 의해 기초적인 논리적 모델링으로 내려 오고

논리적 모델링시에는 흔히 이야기 하는 정규화 과정을 거치게 됩니다.

즉, 차수 정의(1:1, 1:M, N:M)관계는 이미 개념적 모델링에서 처리가 된다는 것입니다.

 DA# 프로그램으로 말하면 플래너 단계에서 이루어 진다고 봅니다.

이에 대한 논리적 모델링 단계에선 관계형 데이타 베이스에 맞는 모델링을 해야 합니다.

마지막 단계에서 역정규화 작업이나.. 여타 작업을 하지만,

이것이 테이블에 대한 분리를 이야기 하지 않습니다.

정규화 단계를 많은 사람들이 알고 있듯이 테이블의 분할이라는 것은

속성에 대한 재정의 (차수의 변경등에 의한)를

통해서 속성에 대한 테이블의 분리로 이루어 질 수 있습니다.

하지만, 논리적 모델링 단계에서는 DBMS의 벤더에 종속되지 않는 모델링이 이루어 져야 하고,

 관계형 데이터베이스의 이론에 충실한 모델링이 이루어 져야 합니다.

1:1 엔티티에 대한 내용은 역정규화시에 통합이 되어야 하고, 업무분석시에 이루어지는 검색조건이나, 여타 조건에 의한 테이블의 분할이라는 것은 DBMS가 정해지고 플랫폼의 정의가 이루어진 후, 물리적 모델링 단계에서 이루어 져야 한다고 봅니다.
저는 1:1 엔티티에 대한 통합은 논리적 모델링 관계에서 무조건적으로 통합되어야 한다고 봅니다.

 

####

BCNF 정규화는
3정규형에서 BCNF 정규형이 되려면 비결정자에의한 함수종속을 제거해야 하는것을 알고계시죠..
비결정자에 의한 함수종속을 제거해서 분해된 BCNF정규형은
결과적으로 모든 속성들이 후보키로서 사용이 가능한 형태로 분해됩니다.
다시 말해 분해된 테이블의 모든 결정자들이 후보키이면
BCNF정규형이라 말합니다
제4정규화는
2정규화 된 테이블은 다대다 관계를 가질수 없다.
이건 따로 예를 안들어도 되겠죠?ㅋㅋ

 

 

#### 제약조건

 

 1. PK  : 기본키 => 유일한값 , NULL(X), Index (기본값:CI)

 2. UQ  : 유니크 => 유일한값 , NULL(1[MS]), Index (기본값:NCI)
          NULL(다[Ora])

 3. FK : 외래키 => 자기/다른 테이블의 PK, UQ를 참조

  참조하는 컬럼의 DataType과 Size가 일치

 4. CK : 범위 설정 => 0 < 값 < 100
   열거 조건 => 값 in (값1, 값2, 값3,,,,)

 5. DF : 기본값

 6. NN : Not Null => Null 값 허용 여부

 

 

Posted by redkite
, |

 

 

 

 

 

# Application

  - Database Server : MS SQL Server

    - Database Engine
# - DBMS (SSMS[DB Obejct / Query]
  SSCM[Service / Network])

#     -  Instance <-- IP (외부접속 연결대상)
 
         1차 이름      2차 이름
   ------------------------------
  * 외부 이름 : HostName    HostName\Test
  * 내부 이름 : MSSQLSERVER    Test

      --> 접속 연결 이름

   로컬 : .   or localhost
   내부 : MSSQLSERVER
   외부 : hosname or IP

      --> DB Engine Service 실행 OS Account

   - Administrator : OS 전체 관리 계정(사용자환경)
   - 일반 OS User  : 일반 사용자 계정
   - Local System  : OS 전체 관리 계정(컴퓨터환경)
   - Local Service : 일반 서비스 계정


      --> Instance 구성정보

  - System Database
     1) master : Instance 전체 구성정보
     2) model  : Database의 기본 틀 제공
     3) msdb   : 운영 업무 자동화의 관련 정보
     4) tempdb : 임시 Database (휘발성)


 
#  - Database : 업무에 따른 공간

#     - Schema : 사전 정의

#   - Object : Table

 

 

# SQL Server  관리 도구

 - SSMS : 개체관리 + 쿼리분석
 - SSCM : 서비스 + 네트워크 설정
 - SQL cmd : DOS 창에서 사용하는 SQL 명령어 도구

 

### 작업 스크립트

 

01. identity.sql

02. UNIQUEIDENTIFIER 데이터 형식.sql

03. HIERARCHYID.sql

04. Date 데이터형식.sql

05. char_varchar.sql

06. Collation.sql

07. null저장공간.sql

08. smallDateTime.sql

09. Time.sql

10. XML_DataConversion.sql

# SQL CMD 명령어

 - sqlcmd /?

C:\Users\Administrator>sqlcmd
1> use testdb
2> go
데이터베이스 컨텍스트가 'testDB'(으)로 변경되었습니다.
1> select * from t1;
2> go
id
-----------

(0개 행 적용됨)
1> insert into t1 values(10)                                                                     ==>  SQL 표준 문법
2> go

(1개 행 적용됨)
1> insert into t1 values(20)
2> insert into t1 values(30)
3> insert into t1 values(40)
4> go

(1개 행 적용됨)

1> insert into t1 values(50),(60),(70)                                                        ==> SQL 서버에서만 사용가능한 문법
2> go

(3개 행 적용됨)
1> select * from T1
2> go
id
-----------
         10
         20
         30
         40
         50
         60
         70

(7개 행 적용됨)

 

#  데이터 값 사용에 대한 확인

 

null저장공간.sql

 

 

 

### XML 데이터 타입으로 변경

 

CreateSampleTbl.sql

 

InsertBuyTbl.sql

 

InsertUserTbl.sql

select * from userTbl
where height > 180
for xml raw('열')

 

- 트리 구조로 변경

  

 

- xml 데이터 값으로 출력

 

- xml db 형태로 변환

 

 

 

 

'01.MS-SQL' 카테고리의 다른 글

[MSSQL]MS-SQL 2일차 - Object 관리  (0) 2013.04.02
[MSSQL]MS-SQL 1일차 - 테이블 / 정규화  (0) 2013.04.01
[MSSQL]MS-SQL 설치  (0) 2013.04.01
[MSSQL]데이터베이스 이동  (0) 2012.12.19
[MSSQL]Windows 64Bit And MS-SQL 32Bit  (0) 2012.12.19
Posted by redkite
, |

[MSSQL]MS-SQL 설치

01.MS-SQL / 2013. 4. 1. 11:49

1. 설치 패키지

 

 

2. 설치 전 최종 단계

 

Posted by redkite
, |

최근에 달린 댓글

최근에 받은 트랙백

글 보관함