ORACLE2009. 11. 21. 13:01
File System과 DataBase System과의 차이 ORACLE

2009/01/07 20:06

작성자: 베레(lsj403)

1.File System 의 단점

-사용이 어렵다.

-응용 프로그래머가 파일의 물리적 데이터 구조를 잘 알아야 함.

-데이터 독립성을 지원 못함.

-데이터의 중복 발생.

-다수 사용자 환경을 지원하지 못함.

-세부적인 사용자 접근 제어 구현이 불가능.

 

2.DataBase의 장점

-데이터 공유 가능.

-데이터 중복 감소

-데이터 불일치 감소

-데이터 보안을 구현

-데이터 표현 및 저장에 있어 일관된 표준 체계를 적용 가능.


Posted by Tiwaz
ORACLE2009. 11. 21. 12:59
데이터베이스의 개념(DB/DBMS/DBS) ORACLE

2009/01/07 19:59

작성자: 베레(lsj403)

1. 데이터베이스(DB:DataBase)

-데이터베이스(DB:Database)는 특정 조직 내에서 다수의 사용자들이 공유(share)할 수 있도록 통합(integrate) 시키고 컴퓨터 저장 장치에 저장(Store)시킨 운영 데이터의 집합.

 

2. 데이터베이스 관리 시스템(DBMS:DataBase Management System)

-데이터베이스를 관리 운영하는 소프트웨어로서 데이터베이스 시스템에서 핵심적인 역할 수행

-데이터베이스와 사용자 응용 프로그램 사이의 중개자로서 모든 응용 프로그램들의 데이터베이스 접근을 대행하여 데이터베이스를 관리해주는 소프트웨어 시스템.

 

3. 데이터베이스 시스템(DBS:DataBase System)

-데이터베이스 시스템은 응용프로그램, 데이터 베이스 관리 시스템, 데이터베이스 등이 통합된 것.

 

4. 데이터베이스 구성 요소

-개체(Entity)

-관계(Relationship)

 

5. 데이터베이스 정규화

-정규화(Normalization)란 한 테이블에서 불필요하게 중복도는 데이터를 분리하여 새로운 단순한 형태를 가지는 여러 개의 테이블로 나누는 것.


Posted by Tiwaz
ORACLE2009. 11. 21. 12:58
 

The following J2EE Applications have been deployed and are accessible at the URLs listed below.

iSQL*Plus URL:
http://localhost.localdomain:5560/isqlplus

iSQL*Plus DBA URL:
http://localhost.localdomain:5560/isqlplus/dba


Posted by Tiwaz
ORACLE2009. 11. 21. 12:53

Installation of Oracle 9i on fedora Core Linux 2,3,4,5 and 6 ORACLE

2008/08/11 00:18

작성자: 베레(lsj403)

복사 http://blog.naver.com/lsj403/memo/77722095

Installation of Oracle 9i (R2) on Fedora Core Linux 2, 3, 4, 5 and 6


This paper (HOWTO) describes step-by-step installation of Oracle 9i database software on Fedora Core 2, 3, 4, 5 and 6.

This paper covers following steps:

Pre-Instalation Tasks

1. Create oracle User Account

Login as root and create te user oracle which belongs to dba group.
su -
# groupadd dba
# useradd -g dba oracle

2. Setting System parameters
Edit the /etc/sysctl.conf and add following lines:
kernel.sem = 250 32000 100 128
kernel.shmmax = 2147483648
kernel.shmmni = 128
kernel.shmall = 2097152
kernel.msgmnb = 65536
kernel.msgmni = 2878
fs.file-max = 65536
net.ipv4.ip_local_port_range = 1024 65000
Note: You need execute "sysctl -p" or reboot system to apply above settings.

Edit the /etc/security/limits.conf file and add following lines:
* - nproc 16384
* - nofile 16384

3. Setting Oracle Enviroment
Edit the /home/oracle/.bash_profile file and add following lines:

Settings for Fedora Core 2,3,4 only. For Fedora Core 5 and 6 use the next settings.
ORACLE_BASE=/opt/oracle
ORACLE_HOME=$ORACLE_BASE/920
ORACLE_SID=MY_ORACLE
LD_LIBRARY_PATH=$ORACLE_HOME/lib
LD_ASSUME_KERNEL=2.4.1
THREADS_FLAG=native
ORACLE_OEM_JAVARUNTIME=/opt/jre1.3.1_15
PATH=$PATH:$ORACLE_HOME/bin

export ORACLE_BASE ORACLE_HOME ORACLE_SID LD_LIBRARY_PATH LD_ASSUME_KERNEL THREADS_FLAG ORACLE_OEM_JAVARUNTIME PATH

Settings for Fedora Core 5 and 6 only. For Fedora Core 2,3,4 use the above settings. Note setting of LD_ASSUME_KERNEL will cause incorrect functionality of FC5 and FC6.
ORACLE_BASE=/opt/oracle
ORACLE_HOME=$ORACLE_BASE/920
ORACLE_SID=MY_ORACLE
LD_LIBRARY_PATH=$ORACLE_HOME/lib
ORACLE_OEM_JAVARUNTIME=/opt/jre1.3.1_15
PATH=$PATH:$ORACLE_HOME/bin

export ORACLE_BASE ORACLE_HOME ORACLE_SID LD_LIBRARY_PATH ORACLE_OEM_JAVARUNTIME PATH

Save the .bash_profile and execute following commands for load new enviroment:
cd /home/oracle
. .bash_profile

4. Create base directory for Oracle

Login as root and create base directory for Oracle ($ORACLE_BASE).
su -
# cd /opt
# mkdir oracle
# chown oracle:dba oracle

Download & Install

1. Download and install required .rpm packages

Some additional packages are required for succesful instalation of Oracle software. To check whether required packages are installed on your operating system use following command:
rpm -q gcc glibc-headers glibc-kernheaders glibc-devel compat-libstdc++ cpp compat-gcc
Note: You don't need glibc-kernheaders installed on FC6 as this package is not shipped with FC6.
If some package is not installed download it from Fedora project website or direct from Core 2, Core 3, Core 4, Core 5, Core 6 locations.

This step is required for Fedora Core 3 and 4 only. Fedora Core 3 is shipped with compat-gcc-8.3.3.4. Fedora Core 4 is shipped with compat-gcc-32-3.2.3. These package are GCC 3.x compiler which are not useful for succesful inatallation. Check whether compat-gcc-8.3.3.4 or compat-gcc-32-3.2.3 is installed. If so then uninstall it using folowing command:
rpm -e compat-gcc
Download the compat-gcc-7.3-2.96.126.i386.rpm package from Core 2 location or from here.


Install the required packages using the rpm command (Note version of packages may change in newer release, so versions for all packages (except compat-gcc package) used in next command are just for example.):
# rpm -ivh gcc-3.4.2-6.fc3.i386.rpm \
glibc-headers-2.3.3-74.i386.rpm \
glibc-kernheaders-2.4-9.1.87.i386.rpm \
glibc-devel-2.3.3-74.i386.rpm \
compat-libstdc++-3.4.2-6.fc3.i386.rpm \
cpp-3.4.2-6.fc3.i386.rpm \
compat-gcc-7.3-2.96.126.i386.rpm


For Fedora Core 4, 5 and 6 only:Install the required additional packages using the rpm command:
# rpm -ivh compat-libgcc-296-2.96-___.rpm \
compat-libstdc++-33-3.2.3-___.rpm \
compat-libstdc++-296-2.96-___.rpm

If all required packages were installed succesfuly then login as root and switch the GCC3 compiler binary with GCC2 compiler binary as following:
su -
# cd /usr/bin
# mv ./gcc ./gcc3
# mv ./gcc296 ./gcc

2. Download the Java Runtime Enviroment (j2re-1_3_1_15-linux-i586.bin) from the Sun website. Keep in mind you need to download j2re1.3.1_11 or higher (Note: Install JRE 1.3.1_1x version only).

Login as root and make the the file executable and then execute it. When the JRE is exracted move the "jre1.3.1_15" di rectory to "/opt" directory.
# chmod +x j2re-1_3_1_15-linux-i586.bin
# ./j2re-1_3_1_15-linux-i586.bin

# mv jre1.3.1_15 /opt/

3. Download the Oracle 9i (9.2.0.4) software from Oracle website.
Extract the files using following command:
gunzip ship_9204_linux_disk1.cpio.gz
gunzip ship_9204_linux_disk2.cpio.gz
gunzip ship_9204_linux_disk3.cpio.gz

cpio -idmv < ship_9204_linux_disk1.cpio
cpio -idmv < ship_9204_linux_disk2.cpio
cpio -idmv < ship_9204_linux_disk3.cpio

When all archives were extracted you've got three directories Disk1, Disk2 and Disk3.
Edit the Disk1/install/linux/oraparam.ini and modify JRE_LOCATION variable and set path to our JRE installation from Step 2.

JRE_LOCATION=/opt/jre1.3.1_15

4. Start the Oracle software installation process.

Now the system is prepared for Oracle software installation. To start the installation process execute the following commands:
cd Disk1
./runInstaller

When network configuration assistant and database configuration assistant has failed during st artup then do following steps:
cd /opt/oracle/920
rm JRE
ln -s /opt/jre1.3.1_15 JRE
su -
# cd /opt/oracle/920/JRE/bin
# ln -s java jre
# cd i386/native_threads
# ln -s java jre

Post-Instalation Tasks

1. Switch back the GCC binaries
su -
# cd /usr/bin
# mv ./gcc ./gcc296
# mv ./gcc3 ./gcc

2. Change of JRE path in Oracle Universal Installer

Edit the $ORACLE_BASE/oui/oraparam.ini file and modify the value of JRE_LOCATION to /opt/jre1.3.1_15

3. (Optional) You may consider to use rlwrap for comfortable work with sqlplus. RPM package for Fedora Core (x86) distribution you can download here.
su -
# rpm -ivh rlwrap-0.24.fedora.i386.rpm
# exit
echo "alias sqlplus='rlwrap sqlplus'" >> /home/oracle/.bash_profile
. /home/oracle/.bash_profile


Common Installation Errors

Unable to load native library: /tmp/OraInstall2005-01-08_11-11-34AM/jre/lib/i386/libjava.so: symbol __libc_wait, version GLIBC_2.0 not defined in file libc.so.6 with link time reference
Solution: Install new JRE 1.3.1 version. Edit the Disk1/install/linux/oraparam.ini and set path to new JRE for JRE_LOCATION variable. For more information see Download & Install section.

/tmp/OraInstall2005-04-26_11-38-19AM/jre/lib/i386/libawt.so: libXp.so.6: cannot open shared object file: No such file or directory
Solution: Install the xorg-x11-deprecated-libs package (for >=FC4 versions). For FC5 and later install libXp package.

/tmp/OraInstall2005-06-14_03-46-25PM/jre/bin/i386/native_threads/java: error while loading shared libraries: /tmp/OraInstall2005-06-14_03-46-25PM/jre/lib/i386/native_threads/libhpi.so: cannot restore segment prot after reloc: Permission denied
Solution: Modify /etc/selinux/config and change value of SELINUX to "disabled" and reboot computer.

Starting Oracle Intelligent Agent.../opt/oracle/920/bin/dbsnmpwd: line 156: 1393 Segmentation fault nohup $ORACLE_HOME/bin/dbsnmp $* >>$DBSNMP_WDLOGFILE 2>&1
/opt/oracle/920/bin/dbsnmpwd: line 156: 1405 Segmentation fault nohup $ORACLE_HOME/bin/dbsnmp $* >>$DBSNMP_WDLOGFILE 2>&1
/opt/oracle/920/bin/dbsnmpwd: line 156: 1416 Segmentation fault nohup $ORACLE_HOME/bin/dbsnmp $* >>$DBSNMP_WDLOGFILE 2>&1
/opt/oracle/920/bin/dbsnmpwd: line 156: 1427 Segmentation fault nohup $ORACLE_HOME/bin/dbsnmp $* >>$DBSNMP_WDLOGFILE 2>&1

Solution: Download and apply patch nr.: 3238244 from http://metalink.oracle.com.

Exception in thread "main" java.lang.InternalError: Can't connect to X11 window server using 'localhost:0.0' as the value of the DISPLAY variable.
Solution: Execute "export DISPLAY=:0.0" (as oracle user) and "xhost +" as user who has opened X session (for example logged in KDE, GNOME, etc.). If the value is other than 127.0.0.1 or localhost you should "xhost +" on client machine.

Error in invoking target install of makefile /opt/oracle/920/ctx/lib/ins_ctx.mk
Error in invoking target install of makefile /opt/oracle/920/precomp/lib/ins_precomp.mk
Error in invoking target install of makefile /opt/oracle/920/plsql/lib/ins_plsql.mk
Error in invoking ntcontab.o of makfile /opt/oracle/920/network/lib/ins_net_client.mk

Solution: Install the compat-gcc-7.3-2.96.126.i386.rpm (gcc 2.96) package and change the GCC binaries. For more information see Download & Install section. In case of Fedora Core 5 take look at next error message.

sed: -e expression #1, char 7: unterminated `s' command error in $ORACLE_HOME/install/make.log
Solution: There is probably bug in bash (FC5 only). Download and install bash package from FC4. I have prepared this package (builded from FC4 src.rpm) for FC5 - Download.
Install it using "rpm -ivh bash-3.0-31.i386.rpm --force".

Initializing Java Virtual Machine from /tmp/OraInstall2006-10-25_01-43-30PM/jre/bin/java. Please wait... /tmp/OraInstall2006-10-25_01-43-30PM/jre/bin/i386/native_threads/java: error while loading shared libraries: libstdc++-libc6.1-1.so.2: cannot open shared object file: No such file or directory - after ./runInstaller execution.
Solution:
su -
# cd /usr/lib
# ln -s libstdc++-3-libc6.2-2-2.10.0.so libstdc++-libc6.1-1.so.2

Start ./runInstaller again.


Last update: 25-10-2006. Comments, suggestions, questions, errors (also grammatical :) )? Feel

'ORACLE' 카테고리의 다른 글

데이터베이스의 개념(DB/DBMS/DBS)  (0) 2009.11.21
iSQL*PLUS Web으로 실행시키기  (0) 2009.11.21
오라클 설치 정리  (0) 2009.11.21
The Index_DESC Hint  (0) 2009.11.11
Installation of Oracle 10g on Centos Linux 5  (0) 2009.11.11
Posted by Tiwaz
ORACLE2009. 11. 21. 12:51

본문스크랩 오라클 설치 정리 ORACLE

2008/08/07 18:34

작성자: 베레(lsj403)

복사 http://blog.naver.com/lsj403/memo/77722012

출처 IT | 인스피런
원문 http://blog.naver.com/503s/60083321411

INSTALL oracle9i on redhat 9.0 

1. 설치전 필요한 페키지
X-Window 필수
gcc-3.2.2-5
cpp-3.2.2-5
glibc-devel-2.3.2-11.9
binutils-2.13.90.0.18-9
compat-gcc-7.3-2.96.118.i386.rpm
compat-libgcj-7.3-2.96.118.i386.rpm
compat-libgcj-devel-7.3-2.96.118.i386.rpm
nss_db-compat-2.2-20.i386.rpm
pdksh-5.2.14-21
libncursers

2. 다운로드 소스
http://otn.oracle.com/software/products/oracle9i/htdocs/linuxsoft.html

 

# gunzip ship_Disk1.cpio.gz                            모든 파일을 압축을 푼다.
# cpio -idmv < Linux9i_Disk1.cpio           이렇게 순서대로 하면 각각 Disk1, DIsk2, DIsk3 라는 디렉터리가 생기면 압축이 풀린다. 

3. 계정 및 그룹생성 시스템 설정
# groupadd dba
# adduser -g dba oracle

# passwd oracle

# chown -R oracle.dba /home/oracle           디렉토리를 오라클이 access 하게 해준다

# chmod  755 /home/oracle


# vi /etc/sysctl.conf
kernel.shmmax = 536870912
kernel.shmmni = 4096
kernel.shmall = 2097152
kernel.sem = 250 32000 100 128
fs.file-max = 65536
net.ipv4.ip_local_port_range = 1024 65000

# vi /etc/security/limits.conf
oracle soft nofile 65536
oracle hard nofile 65536
oracle soft nproc 16384
oracle hard nproc 16384

만약 리붓팅하지 않을려면 다음과 같이한다.
# echo 250 32000 100 128 > /proc/sys/kernel/sem
# echo 536870912 > /proc/sys/kernel/shmmax
# echo 4096 > /proc/sys/kernel/shmmni
# echo 2097152 > /proc/sys/kernel/shmall
# echo 65536 > /proc/sys/fs/file-max
# echo 1024 65000 > /proc/sys/net/ipv4/ip_local_port_range


3. 환경변수 설정(여기서 부터 oracle 계정으로 바꾼다.)


$ vi .bash_profile
export ORACLE_BASE=/home/oracle
export ORACLE_HOME=$ORACLE_BASE/product/9.2.0.1
export ORACLE_OWNER=oracle
export ORACLE_SID=oracle
export ORACLE_TERM=xterm
#export TMPDIR=$ORACLE_BASE/tmp
#export TNS_ADMIN=$ORACLE_HOME/network/admin
export NLS_LANG='AMERICAN_AMERICA.KO16KSC5601'
export ORA_NLS33=$ORACLE_HOME/ocommon/nls/admin/data
export LD_LIBRARY_PATH=$ORACLE_HOME/lib:$ORAClE_HOME/oracm/lib:/lib:/usr/lib:/usr/local/lib
export LANG=C
export LD_ASSUME_KERNEL=2.4.1
export THREADS_FLAG=native
export PATH=$PATH:$ORACLE_HOME/bin:$ORACLE_HOME/oracm/bin

CLASSPATH=$ORACLE_HOME/JRE:$ORACLE_HOME/jlib:$ORACLE_HOME/rdbms/jlib:$ORACLE_HOME/network/jlib


4. 3번의 과정이 성공적으로 끝났다면 설치창이 뜬다. 

$ su -             

# xhost +          root 계정에서 실행

xhost +   엔터로 모든 계정에서 X window 를 사용할 수 있게 해 준 후에
오라클 홈페이지에서 다운로드 받은 설치파일 위치로 간다.
본인은  /home/oracle 위치에 다운 받았다. 압축푼 위치의 Disk1 로 이동하면
runInstaller   라는 파일이 있다.  이걸 실행시킨다.

# su - oracle

$ cd /home/oracle/Disk1

$ ./runInstaller                       <- 오라클 소스압축푼 디렉터리

Oracle Universal Installer 가 뜨면서 여러가지를 물어본다
/home/oracle/oraInventory  을 oracle_base directory 로 한다
UNIX Group Name 은 dba 로 한다

Full path name for Oracle Home:  는
  /home/oracle/product/9.2.0  로 한다

root 권한으로 특정 파일(/tmp/orainstRoot.sh)을 실행해야 하라고 하면 다른 터미널 창에서
다음과 간이 하면 아래에 다음 메시지가 전시된다.

# /tmp/orainstRoot.sh

 

“Oracle9i Database 9.2.0.1.0”을 선택하여 데이터베이스를 구성합니다.
“제품 언어...”를 클릭합니다.

Oracle DB에서 사용할 문자 셋을 설정합니다. 이곳 설정은 $HOME/.bash_profile 의
NLS_LANG의 값과 일치해야 합니다. Default character set 이 KO16KSC5601이므로
Database Character Set을 default로 놓고 “다음” 버튼을 물러 계속 설치를 진행합니다.

설치 유형을 묻는 화면입니다. 여기서는 Enterprise Edition을 선택하여 설치합니다.
Enterprise Edition은 모든 컴포넌트가 설치 됩니다. “다음” 버튼을 클릭합니다.


“설치 유형”에서 “Database Configuration”으로 넘어가는 중간 화면 입니다.


Database Suite에서 General Purpose를 선택합니다. “다음”버튼을 클릭하여 계속 설치를 진행합니다.

Global Database 이름, SID 등을 정해 줍니다.


다음을 계속 누르면 설치가 시작됩니다.

 

root 권한으로 특정 파일(/home/oracle/product/9.2.0.1/root.sh )을 실행해야 하라고 하면 다른 터미널 창에서
다음과 간이 하면 아래에 다음 메시지가 전시된다.

# /home/oracle/product/9.2.0.1/root.sh 

 

설치 진행 ~~~

 

password 설정 창 뜨면 설정하고

설치 계속~~

error 창 하나뜸 그냥 확인 하고 next

설치 계속~~

 

완료

Posted by Tiwaz
ORACLE2009. 11. 11. 23:37

The Index_DESC Hint
The INDEX_DESC hint causes indexs to be scanned in descending order (of their indexed value or order), which is the opposite of the INDEX and INDEX_ASC hints. This hint is overridden when the query has multiple tables, because the index needs to be used in the normal ascending order to be joined to the other table in the query. Some restrictions for this include that it does not work for bitmap indexes or for descending indexes, that it causes the index to be scanned in ascending order, and that it does not work across partitioned index boundaries but performs a descending index scan of each partition.

Syntax
select /*+ INDEX_DESC (table index1, index2...) * column1, ...

Example
select /*+ INDEX_DESC(emp deptno_idx) */ empno, ename, deptno
from emp
where deptno = 1;

The INDEX_DESC processes an index in descending order of how it was built. This hint will not be used if more than one table exists in the query.

 

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

출처는 잘모르겠습니다~

문제시 삭제처리하겠습니다^^


개발을 하다보면 SQL문을 자주 사용하게 되는데...
최소한 Toad등에서 Query에 대해 Plan한번만 떠 보세요... 그러면 그 쿼리가 어느 정도의 성능을 내는지는 대충 짐작하실 수 있습니다. 그런 다음 테이블의 인덱스를 적절히 사용하는지 확인만 하면 최소한 나쁜 쿼리는 작성하지 않게 됩니다. (인덱스를 사용하는 경우가 최선의 성능을 보장 하지는 않습니다)

아래 내용을 참고하시고 사용하는 DB가 오라클이라면 반드시 힌트에 대해 관심을 가지시기 바라구요 옵티마이저 수행 경로가 정상적인 경우와 비정상인 경우 성능 차이는 장난 아닙니다. 심지어 10배 이상 나는 경우도 있구요,,,
(힌트는 Oracle Optiomizer의 수행경로를 변경 시키는 역할을 합니다.)

인덱스 힌트를 사용하게 되면 오라클 옵티마이저는 기술된 인덱스를 써야 한다는 것을 알게되며 이 경우 Table Full Scan을 하지 않게 되죠... 물론 사용되는 인덱스에 대해 COST는 계산하지 않고 존재하는 인덱스라면 사용을 한다는 이야깁니다...

만약 인덱스 힌트가 사용되지 않았지만 인덱스를 사용할 수 있는 경우라면 여러 인덱스중 COST가 적게 드는 인덱스를 하나 선택하여 사용하게 되구요...


사용 형식은 아래와 같구요...

/*+ INDEX ( table [index [index]...] ) */

table은 테이블 명이나 Alias 명 입니다.
index에는 사용되는 인덱스명을 쓰시면 되구요,

예)
select /*+ INDEX(idx_emp_job) */
       ename,
       job
from emp
where job= '프로그래머';

DELETE /*+ INDEX(idx_emp_status)*/
FROM emp_status
WHERE status = '휴직';

*** INDEX_ASC : INDEX 힌트와 거의 유사하며 단지 다른 부분이라면 인덱스 영역의 검색되는 데이터가 오름차순으로 Scan 되는 것이죠...

INDEX_ASC
/*+ INDEX_ASC(table index[index .. index]) */


*** INDEX_DESC : 이 힌트 역시 INDEX힌트와 유사하며 단지 인덱스 영역의 검색되는 데이터가 내림차순으로 Scan 되는 것이죠...

/*+ INDEX_DESC (table index[index .. index]) */

위 INDEX_ASC나 INDEX_DESC를 적절히 사용하시면 ORDER BY 구문을 사용하지 않아도 되는 경우가 대부분 입니다.(ORDER BY를 많은 건의 데이터에 대해 사용하시면 성능에 악 영향을 줍니다)

emp 테이블에 ename으로 인덱스가 있다면...

select ename, sal
from emp
order by ename

==>

select /*+ index_asc(emp) */
         ename, sal
from emp
where ename > '가'  -- 한글 이름을 사용한다고 했을 때
(이 경우 order by를 사용하지 않았지만 데이터는 ename으로 오름차순 정렬되어 나옵니다)


*** FULL : 인덱스 사용하지 않고 Table을 FULL Scan하라는 힌트
만약 성별처럼 "M" 아니면 "F"만 가지는 경우 분포도가 50%이므로 인덱스를 사용하는 것보다 인덱스를 사용하지 않는 경우가 성능에 효율적일 수 있습니다. 이러한 경우 사용하는 힌트죠...

사용 형식
/*+ FULL (table) */

select /*+ FULL(emp) */ ename, sal
from emp
where sex = 'M'

*** NO_INDEX : 기술된 테이블에 대해서는 인덱스를 사용하지 말라는 의미

select /*+ NO_INDEX(emp) */ ename, sal
from emp where sex = 'M';


Posted by Tiwaz
ORACLE2009. 11. 11. 23:34

//root 로 로그인
#su - 

 /*커널 매개변수 확인 및 설정(변수 값이 클경우 안바꿔도 상관없음)
 #/sbin/sysctl -p
 #/sbin/sysctl -a | grep shm
 #/sbin/sysctl -a | grep sem
 #/sbin/sysctl -a | grep file-max
 #/sbin/sysctl -a | grep ip_local_port_range
 */


 //매개변수 설정
#vi /etc/sysctl.conf 

 #kernel.shmall = 2097152
 #kernel.shmmax = 2147483648
 kernel.shmmni = 4096
 # semaphores: semmsl, semmns, semopm, semmni
 kernel.sem = 250 32000 100 128
 #fs.file-max = 65536
 net.ipv4.ip_local_port_range = 1024 65000
 net.core.rmem_default=262144
 net.core.rmem_max=262144
 net.core.wmem_default=262144
 net.core.wmem_max=262144


//매개변수 적용
#/sbin/sysctl -p 


//제한값 설정
#vi /etc/security/limits.conf  

 *               soft    nproc   2047
 *               hard    nproc   16384
 *               soft    nofile  1024
 *               hard    nofile  65536


//설정
#vi /etc/pam.d/login 

 session    required     /lib/security/pam_limits.so


#SELINUX=disabled
 

//필수 패키지 설치
#yum install setarch-2* make-3* glibc-2* libaio-0* compat-libstdc++-33-3* compat-gcc-34-3*
compat-gcc-34-c++-3* gcc-4* libXp-1* openmotif-2* compat-db-4*


//오라클 그룹 생성
#groupadd dba


//오라클 유저 생성
#useradd -g dba oracle
#passwd oracle  <--패스워드는 각자알아서


//설치디렉토리 생성
#mkdir -p /u01/app/oracle/product/10.2.0/db_1


//권한 설정
#chown -R oracle:dba /u01


//네트워크 확인
#xhost +127.0.0.1


//release 명 변경
#vi /etc/redhat-release
 centOS 삭제후 -> redhat-4 추가


//login to ORACLE


//oracle 환경 변수 설정
$vi /home/oracle/.bash_profile

 # Oracle Settings
 TMP=/tmp; export TMP
 TMPDIR=$TMP; export TMPDIR

 ORACLE_BASE=/u01/app/oracle; export ORACLE_BASE
 ORACLE_HOME=$ORACLE_BASE/product/10.2.0/db_1; export ORACLE_HOME
 ORACLE_SID=orcl; export ORACLE_SID
 ORACLE_TERM=xterm; export ORACLE_TERM
 PATH=/usr/sbin:$PATH; export PATH
 PATH=$ORACLE_HOME/bin:$PATH; export PATH
 NLS_LANG=American_America.AL32UTF8; export NLS_LANG 

 LD_LIBRARY_PATH=$ORACLE_HOME/lib:/lib:/usr/lib; export LD_LIBRARY_PATH
 CLASSPATH=$ORACLE_HOME/JRE:$ORACLE_HOME/jlib:$ORACLE_HOME/rdbms/jlib; export CLASSPATH

 if [ $USER = "oracle" ]; then
   if [ $SHELL = "/bin/ksh" ]; then
     ulimit -p 16384
     ulimit -n 65536
   else
     ulimit -u 16384 -n 65536
   fi
 fi

//oracle 설치파일 download

http://www.oracle.com/technology/software/products/database/index.html

10201_database_linux32.zip

압축풀고 압축푼 폴더에가서
 

//oracle 설치 시작
$./runInstaller


'ORACLE' 카테고리의 다른 글

오라클 설치 정리  (0) 2009.11.21
The Index_DESC Hint  (0) 2009.11.11
Oracle 10g 의 휴지통 기능  (0) 2009.11.11
프로시져, 트리거의 이해-2009/02/20  (0) 2009.11.11
PL/SQL의 이해-2009/02/19  (0) 2009.11.11
Posted by Tiwaz
ORACLE2009. 11. 11. 23:32

Oracle10g 에서 테이블을 삭제하면 9i 이전 버전의 경우 바로 삭제 된다.
하지만 Oracle 10g의 경우 윈도우의 휴지통과 같은 기능을  제공한다.

테이블을 DROP 하면 BIN$xxxxxxx 과 같이 테이블이 생성된다.
이 테이블은 언제든지 되살릴 수 있으며 쿼리도 모두 된다.
DESC "BIN$xxxxxxx";
SELECT * FROM "BIN$xxxxxxx";

이 BIN 테이블을 완전히 삭제하기 위해서

SQL> purge recyclebin;



다시 복구하려면

SQL> flashback table [TABLE_NAME] to before drop;


무조건 DROP 하고 싶다면

SQL> drop table [TABLE_NAME] purge;
명령으로 완전히 삭제 할 수 있다.

 


'ORACLE' 카테고리의 다른 글

The Index_DESC Hint  (0) 2009.11.11
Installation of Oracle 10g on Centos Linux 5  (0) 2009.11.11
프로시져, 트리거의 이해-2009/02/20  (0) 2009.11.11
PL/SQL의 이해-2009/02/19  (0) 2009.11.11
내장함수의 이해-2009/02/18  (0) 2009.11.11
Posted by Tiwaz
ORACLE2009. 11. 11. 21:30

--emp_process 프로시져 만들고
--SQL> set serveroutput on
--SQL> exec emp_process

--emp_process2 프로시져 만들고 (부서별 조회)
--SQL> exec emp_process2

--emp_process3 프로시져를 만들고 (업데이트)
--SQL> exec emp_process3

--test4,test5,
--페키지 emp_comm

--dbms_job 패키지
--일정 시간 간격으로 DB작업을 수행
--1. submit : 새로운 job를 등록하는 프로시져
--2. run : 등록된 job을 실행하는 프로시져
--3. remove : 등록된 job을 제거하는 프로시져

create table job_table(
seq number(5),
job_date date
);
--프로시저 만들기 JOB_TEST
--SQL> var job number;
--SQL> exec dbms_job.submit(:job,'job_test;' , sysdate, 'sysdate+10/36000';
--SQL> exec dbms_job.run(:job);
--SQL> exec dbms_job.remove(:job);

--트리거(Trigger)
--테이블의 변경을 자동 감지해서 다른 테이블을 작업을 수행
--예를 들어 게시물이 등록되면 게시물테이블에 데이터가 입력되고,
--게시물카운트테이블에도 데이터가 입력되게 하겠다.
--로깅, 보안, 감사에 많이 쓰임

--트리거의 구성요소
--1.트리거의 유형
--1)문장레벨의 트리거 : 테이블에 update, insert, delete가 일어나면
--   단한번만 트리거를 발생시킴(트리거의 수 = 1)
--2)행레벨의 트리거 : 테이블에 update,insert,delete가 일어나면
--   모든행에 대해 트리거를 발생시킴(트리거의 수 = 행의 수)
--2. 트리거의 타이밍
--1) before : 테이블에 update, insert, delete 가 일어나기 전
--2) after : 테이블에 update, insert, delete 가 일어난 후
--3. 트리거의 이벤트
--1) update
--2) insert
--3) delete
--test1_trigger
--sql)update emp set sal = sal * 1.0;

create table dept_same (
deptno number(2),
dname varchar2(14),
loc varchar2(10),
o_deptno number(2),
o_dname varchar2(14),
o_loc varchar2(10),
gubun varchar2(10),
chk date
);

--test2_trigger 생성
--SQL> insert into dept values(99,'CCC','SEOUL');
--update dept set loc = 'busan' where deptno=99;
--delete from dept where deptno=99;

--트리거의 상태 변경
--1. 트리거 활성화/비활성화
--alter tirgger 트리거 이름 enable
--alter tirgger 트리거 이름 disable
--2. 테이블에 관련된 모든 트리들을 활성화/비활성화
--alter table 테이블명 enable all triggers;
--alter table 테이블명 disable all triggers;
--3. 트리거 재컴파일
--all trigger 트리거명 compile;
--4. 트리거 제거
--drop trigger 트리거명;

--데이터 사전
--사용자의 객체 정보 : user_objects
select object_name, object_id, object_type, created, timestamp, status
from user_objects;
select object_name from user_objects where object_type='PROCEDURE';

-- 소스코드 : user_source
select name, type, line, text
from user_source where name='TAX';
select name, type, line, text
from  user_source where name='TEST5';

-- 사용자의 에러 정보 : user_errors
select * from user_errors;

--사용자의 트리거 정보 : user_triggers
select trigger_name, trigger_type, triggering_event, table_name, status from

user_triggers;

--사용자 객체들의 상호참조 정보 : user_dependencies
select * from user_dependencies where referenced_name = 'EMP';
--사용자의 테이블 정보
select * from user_tables;

--사용자의 뷰 정보
select * from user_views;

--사용자 인덱스 정보
select * from user_indexes;

--사용자의 제약조건 정보
select * from user_constraints;

--바인드 관련 자료
--http://blog.naver.com/nkmin80?Redirect=Log&logNo=140032147


Posted by Tiwaz
ORACLE2009. 11. 11. 21:27

-- PL/SQL의 종류
-- 1. Anonymous Procedure (이름없는 프로시져)
-- 수행할때마다 컴파일해서 연산/결과를 출력
-- 2. Stored Procedure (이름있는 프로시져)
-- 컴파일하면 오라클에 PCODE(컴파일된코드) 형태로 저장되었다가
-- 호출하면 연산/결과를 출력
-- 3. Stored Function (이름있는 함수)
-- 오라클에 내장되어 있는 내장함수들과 사용자가 만든 사용자정의함수로 분류
-- 오라클에 PCODE(컴파일된코드) 형태로 저장되었다가 호출하면 연산하고
-- 결과를 반환
-- 4. Package
-- 비슷한 기능을 하는 함수/프로시져를 묶음
-- 선언부와 구현부로 나누어서 작성
-- 5. Trigger
-- 테이블에 데이터의 입출력을 감지해서 다른 테이블에 입출력하는 기능

-- Stored Procedure
create table log_table (
userid varchar2(10),
log_date date
);

select * from log_table;

-- 매개변수의 모드(mode)
-- in : 값을 프로시져 외부에서 받아오는 매개변수 (기본값)
-- out : 프로시져의 연산결과를 외부로 보내는 매개변수
-- in out : 값을 받아와서 외부르 보내는 매개변수

create sequence s_emp_id
start with 25;

create table top_dogs (
name varchar2(10),
salary number(7,2)
);


-- Stored Function (저장함수)
-- 1. 오라클 내장함수 : 오라클에 내장되어 있는 함수
-- 2. 사용자 정의함수 : 사용자가 생성한 함수

-- 실습
-- 1. 핸드폰번호를 입력하면 010-1234-1234 형식으로 출력해주는 프로시져 hp_proc
-- 실행 : exec hp_proc('01012341234');
-- 결과 : 010-1234-1234
-- 2. 문자열을 입력하면 문자열의 길이를 리턴하는 함수 str_func
-- 실행 : select str_func('안녕하세요!') from dual;
-- 결과 : 6
-- 3. 학생정보 입력/삭제
create table student(stdno number, stdname varchar2(10));
-- * record타입으로 학생정보 저장
-- 입력 : 프로시져 registStudent - 학생번호(number), 학생명(varchar2)
--   실행 : exec registStudent(10, '홍길동')
--   결과 : 홍길동 학생이 등록되었습니다. or 10번 학생이 있습니다.
-- 삭제 : 프로시져 deleteStudent - 학생번호(number)
--   실행 : exec deleteStudent(10)
--   결과 : 10번 학생이 삭제되었습니다. or 10번 학생은 없습니다.
-- 수정 : 프로시져 updateStudent - 학생번호(number), 학생명(varchar2)
--        (학생명 수정되도록)
--   실행 : exec updateStudent(10, '강감찬')
--   결과 : 10번 학생이 수정되었습니다. or 10번 학생은 없습니다.
-- 목록 : 프로시져 listStudent (커서 이용)
--   실행 : exec listStudent
--   결과 : 학생리스트가 보여진다.

Posted by Tiwaz
ORACLE2009. 11. 11. 21:23

select employee_id, first_name, last_name
from employees
where employee_id = :emp;

create table score(
score number);

insert into score values(100);
insert into score values(0);
insert into score values(null);

select avg(score), count(*) from score;
select avg(nvl(score, 0)), count(*) from score;

select department_id, sum(salary) from employees
group by department_id
order by department_id;

--------------------------------------------------
--scott
-------------------------------------------------
--built-in function (오라클 내장함수)
---------------------------문자함수
--ascii 코드값에 해당하는 문자
select chr(75) from dual;

-- 문자열 접합
select concat(concat(ename, ' is a '), job) from emp;

-- 첫글자들을 대문자로
select initcap('i am a boy') from dual;

-- 소문자로
select lower('Mr, Smith') from dual;

--대문자로
select upper('Mr, Smith') from dual;

--왼쪽채우기 (전체 15자리 왼쪽 나머지 공간은 *)
select lpad('Page 1', 15, '*') from dual;

--오른쪽채우기 (전체 15자리 오른쪽 나머지 공간은 *)
select rpad('Page 1', 15, '*') from dual;

--왼쪽 지우기 (왼쪽에 x나 y가 나오면 제거-안나올때까지)
select ltrim('xyxXxyLast Word', 'xy') from dual;

--문자열 대체
select replace ('JACK and JUE', 'J', 'BL') from dual;

--부분 문자열 추출 (인덱스 3에서 2개-인덱스는 1부터 시작)
select substr('abcdefg',3,2) from dual;
select substr('abcdefg',3) from dual;
select substr('abcdefg',-3,2) from dual;

--문자의 유니코드값
select ascii('뷁') from dual;

--첫번째인자문자열에서 두번째 문자열이
--세번째인자문자열에서 네번째인자번째나온 곳의 인덱스
select instr('CORPORATE FLOOR','OR',3,2) from dual;
select instr('CORPORATE FLOOR','OR',-3,2) from dual;

--문자열의 길이
select length('안녕하세요!') from dual;
select lengthb('안녕하세요!') from dual;

--가장큰것(각각의 문자를 비교하여 각각 큰거 & 작은거 비교)
select greatest('HARRY', 'HARIOT', 'HALORD') from dual;

--가장 작은것
select least('HARRY', 'HARIOT', 'HALORD') from dual;

-- null 대체
--nvl : 첫번째 인자가 null이면 두번째 인자, 아니면 첫번째 인자.
select nvl(sal,0), nvl(ename,'*'), nvl(hiredate, '02/11/11') from emp;

----------------------------------시스템 함수
select sysdate from dual;
select systimestamp from dual;
select user from dual;

----------------------수학함수
--절대값
select abs(-15) from dual;

--올림값
select ceil(15.7) from dual;

--내림값
select floor (15.7) from dual;

--버림값
select trunc(15.7) from dual;

--cosine
select cos(180*3.14/180) from dual;

--e의 몇 승
select exp(4) from dual;

--log
select log(10, 100) from dual;

--나머지
select mod(11,4) from dual;

--승
select power(3,2) from dual;

--반올림
select round(15.193, 1) from dual;
select round (15.193, -1) from dual;

-------------------------------날짜함수
--월더하기
select hiredate, add_months(hiredate, 1)
from emp where empno=7782;

--해당 월의 마지막날
select hiredate, last_day(hiredate) from emp;

--시간대 변경
select hiredate, new_time(hiredate, 'GMT', 'PDT') from emp;

--개월의 차
select hiredate, months_between(sysdate, hiredate) from emp;

------------------------------변환 함수

--MM:월
--MON:세글자 영문 월
--MONTH:전체글자 영문 월
--D:그주의 일 수(1:일요일)
--DD:날짜
--DY:요일을 세글자 영문
--DAY:요일의 전체 이름
--YYYY:네자리 표현한 연도
--YY:두자리로 표현한 연도
--HH:12시간으로 표시, HH24:24시간으로 표시
--MI:분
--SS:초
select sysdate, to_char(sysdate, 'D') from dual;
--2009/02/18 12:10
select sysdate, to_char(sysdate, 'YYYY/MM/DD HH24:MI') from dual;
--02일 ==> 2일 (앞에 0제거)
select ename, to_char(hiredate, 'fmDD-MM-YY') from emp;

--문자열을 숫자로 변환
select to_number('100')+200 from dual;
select '100'+200 from dual;

--숫자를 형식에 맞게 문자로 변환
--숫자혀익요소 9(숫자하나), 0(자리가비면 0으로), $(달러).(소수점),(콤마)
select to_char(12506, '$9099,99') from dual;
select '\'||to_char(1234567, '90999,99') from dual;

--날짜의 형식을 변경
select sysdate, to_date('09/07/01', 'DD-MM-YY') from dual;

-- 9i버젼에서 추가된 함수
--nvl2(첫번째인자가 null이면 세번째 인자 null이 아니면 두번째 인자)
select empno, ename, nvl2(comm, comm*1.1, 0) from emp;
--nullif(같으면 null, 다르면 첫번째 인자)
select empno, ename, nullif(comm,0) from emp;
--coalesce(null이 아닌 첫번째 인자)
select coalesce(comm, sal) from emp;
select coalesce(null,null,null,3,null) from dual;
--trim (8i에 추가)
select ename, trim(LEADING 'A' FROM ename) as trim
from emp
where ename like 'A%';

select ename, trim(TRAILING 'N' FROM ename) as trim
from emp
where ename like '%N';

select ename, trim(BOTH 'A' FROM ename) as trim
from emp
where ename like '%';

--------------------------------------복수행 함수
select count(*) from emp;
select count(empno) from emp;
select sum(sal) from emp;

select avg(sal) from emp;
select avg(nvl(sal,0)) from emp;

select max(sal), min(sal) from emp;

--입사일이 가장 늦은 사람과 이른 사람의 일수 차
select max(hiredate)-min(hiredate) from emp;

--부서별 평균 급여
select avg(nvl(sal,0)), deptno
from emp
group by deptno;

--그룹에 조건을 줄때는 having
--그룹에 속하는 사원수가 2보다 크다라는 조건
select deptno, count(*), sum(sal)
from emp
group by deptno
having count(*)>2;

--decode
--decode(expr, a, r1,b,r2,default)
--expr을 평가해서 a이면 r1, b이면 r2, 나머지 모든 경우 default 반환
select job, sal, decode(job, 'ANALYST', sal*1.10,  'CLERK', sal*1.15,
  'MANAGER',sal*1.20, sal) "인상된 급여"
from emp;

--1월 부터 6월 까지 월별로 입사한 사원의 수와 1~6월 전체 입사한 사원의 수
select
count(decode(extract(month from hiredate), '1', 1)) "1월",
count(decode(to_char(hiredate, 'MM'), '02', 1)) "2월",
count(decode(to_char(hiredate, 'MM'), '03', 1)) "3월",
count(decode(to_char(hiredate, 'MM'), '04', 1)) "4월",
count(decode(to_char(hiredate, 'MM'), '05', 1)) "5월",
count(decode(to_char(hiredate, 'MM'), '06', 1)) "6월", count(*) "1월~6월"
from emp
where to_char(hiredate,'MM')>='01' and to_char(hiredate,'MM')<='06';

--case
select job, sal,
  case
    when job='ANALYST' then sal*.10
    when job='CLERK' then sal*1.15
    when job='MANAGER' then sal*1.20
    else sal
  end
from emp;

--사원들의 입사일의 요일을 한자로
select ename, hiredate,
  case
    when to_char(hiredate,'DY')='월' then '月'
    when to_char(hiredate,'DY')='화' then '火'
    when to_char(hiredate,'DY')='수' then '水'
    when to_char(hiredate,'DY')='목' then '木'
    when to_char(hiredate,'DY')='금' then '金'
    when to_char(hiredate,'DY')='토' then '土'
    when to_char(hiredate,'DY')='일' then '日'
  end
from emp;


Posted by Tiwaz
ORACLE2009. 11. 11. 21:21

-- 오라클 객체
-- 1. table
-- 데이터를 저장하는 객체
-- 2. index
-- 데이터 검색속도 증가를 위한 객체
-- 3. view
-- 테이블(들)의 데이터를 보호할 목적으로 사용되는 객체
-- 4. sequence
-- 연속적인 일련번호 생성을 위한 객체
-- 5. synonym
-- 객체의 이름을 간략하게 하기위한 객체

-- Data Dictionary (데이터사전)
-- 데이터에 대한 데이터(MetaData)를 조회할 목적의 뷰들
-- dictionary 조회
select * from dictionary;
-- 사용자의 테이블들
select * from user_tables;
-- 사용자의 인덱스들
select * from user_indexes;
-- 사용자의 뷰들
select * from user_views;
-- 사용자의 제약조건들
select * from user_constraints;

-- 테이블 생성 기본문법
create table dept1 (
deptno number(2),
dname varchar2(13),
loc varchar2(14)
);
-- 테이블 복사
create table dept2
as
select * from dept1;
-- 테이블 목록
select * from tab;
-- 테이블의 컬럼 추가
alter table dept1 add (bigo varchar2(15));
desc dept1;
-- 테이블의 컬럼 변경
alter table dept1 modify (bigo varchar2(30));
-- 테이블의 데이터 삭제 (delete + commit)
truncate table dept1;
-- 테이블명 변경
rename dept2 to dept3;
select * from tab;
-- 테이블 제거
drop table dept3;
-- 주석 달기
comment on table dept1 is '부서정보 테이블입니다!';
select * from user_tab_comments where table_name='DEPT1';
comment on column dept1.deptno is '부서코드';
select * from user_col_comments where table_name='DEPT1';

-- 제약조건 (constraints)
-- 데이터 무결성(integrity)을 지킬 목적으로 컬럼레벨이나 테이블레벨에
-- 부여하는 제약 사항

-- 제약조건들
-- 1. primary key : not null + unique
-- 2. foreign key : 다른테이블의 primary key컬럼의 값을 참조하는 컬럼
-- 3. unique : 컬럼의 값이 유일, 단 null은 여러개 입력될 수 있음
select 1 from dual where null=null;
select 1 from dual where null is null;
-- 4. not null : 컬럼에 값이 null이 입력될 수 없음
-- 5. check : 컬럼에 입력되는 값에 대해 체크
-- 6. default : 컬럼에 입력되는 기본값

-- 제약조건의 특징
-- 사용자에 의해 발생한 잘못된 DML문을 수행되지 않도록 할 목적
-- 제약조건에 대한 모든 정보는 dictionary에 저장된다.
-- 제약조건을 활성화(enable), 비활성화(disable)할 수 있다.
-- 하나의 컬럼에 여러 제약조건을 부여할 수 있다.
-- 여러개의 컬럼에 하나의 제약조건을 부여할 수 있다.
-- 제약조건은 오라클 서버가 관리한다.

-- 제약조건의 유형
-- 1. column level constraints (컬럼레벨제약)
-- 하나의 컬럼에 제약 조건을 정의할 때 사용
-- create, alter 문장으로 컬럼을 정의할 때 데이터 타입 뒤에 정의
-- 위에 있는 모든 제약조건을 컬럼레벨로 모두 부여할 수 있음
-- 2. table level constraints (테이블레벨제약)
-- 하나의 컬럼에 여러개의 제약조건을 부여할때 주로 사용
-- not null제약조건은 table level로 부여할 수 없음

create table dept9 (
deptno number(2) constraint dept9_deptno_pk primary key,
dname varchar2(15),
loc varchar2(1));

drop table dept9;

-- 제약조건명 검색
select constraint_name from user_constraints;
-- 제약조건 추가
alter table dept9 add (constraint dept9_deptno_nn primary key(deptno));

create table dept10 (
deptno number(2) constraint dept10_deptno_pk primary key,
dname varchar2(15),
loc varchar2(1));

create table emp10 (
empno number(4) constraint emp10_empno_pk primary key,
ename varchar2(15),
deptno number(2) constraint emp10_deptno_fk references dept10(deptno));

create table emp11 (
empno number(4) constraint emp11_empno_pk primary key,
ename varchar2(15) constraint emp11_ename_uq unique,
deptno number(2)
);

alter table emp11 add (constraint emp11_deptno_fk foreign key(deptno)
references dept10(deptno));

alter table emp11 add (constraint emp11_deptno_uq unique(deptno));

create table dept12 (
deptno number(2),
dname varchar2(15),
loc char(1) constraint dept12_loc_ck check (loc in ('1','2'))
);

alter table dept12 add (constraint dept12_loc_ck2 check (loc in ('1','2')));

create table dept13 (
deptno number(2),
dname varchar2(15) not null,
loc char(1)
);

select * from user_constraints;

-- 제약조건 삭제
alter table dept12 drop constraint dept12_loc_ck2;
-- 제약조건 비활성화
alter table dept12 modify constraint dept12_loc_ck disable;
-- 제약조건 활성화
alter table dept12 modify constraint dept12_loc_ck enable;


---------------------------------------------------------
-- index
---------------------------------------------------------
--인덱스는 테이블 검색속도를 향상시키기 위한 객체
--주로 B*Tree인덱스를 사용
--- 인덱스를 사용해야 할 때
--1. where절에 자주 등장하는 컬럼
--2. 검색결과가 전체 행의 10%미만인 경우
--- 인덱스를 사용하지 말아야 할 때
--1. 데이터가 적은 (보통 행이 몇천개 이하) 경우
--2. where절에 자주 등장하지 않는 컬럼
--3. 테이블이 자주 수정,삽입,삭제될때
--- 인덱스의 종류
--1. single index : 단일컬럼으로 만들어지는 인덱스
--create index i_emp_ename on emp(ename)
--2. concanated index : 복합컬럼(두개 이상의 컬럼)으로 만들어지는 인덱스
--create index i_emp_empno_ename on emp(empno, ename)
--3. unique index : 인덱스를 생성할 컬럼의 값이 중복되지 않는 경우
--create unique index i_emp_empno on emp(empno)
--4. non-unique index : 인덱스를 생성할 컬럼의 값이 중복되는 경우
--create index i_emp_ename on emp(ename)
--5. function-based index : 컬럼들의 연산결과를 토대로 만든 인덱스
--create index i_emp_sal_comm on emp(sal-comm)

-- 인덱스 생성
create index i_emp_ename on emp(ename);
create unique index i_emp_empno on emp(empno);

-- 인덱스 확인
select * from user_indexes;

-- 인덱스 제거
drop index i_emp_ename;

---------------------------------------------------
-- view
---------------------------------------------------
-- 테이블 데이터를 보호할 목적으로 테이블(들)의 일부데이터를
-- 추출해서 만든 가상 테이블
-- materialized view를 제외하면 view는 물리적으로 데이터를
-- 저장하지 않음. 간단히 말해서 view는 테이블(들)의 select문
select e.empno, e.ename, d.dname
from emp e, dept d
where e.deptno = d.deptno;

-- 뷰 생성
create or replace view view_emp
as
select e.empno, e.ename, d.dname, d.deptno
from emp e, dept d
where e.deptno = d.deptno;

-- 사용자 뷰 확인
select * from user_views;

-- view를 통한 테이블 select
select * from view_emp;

-- force : 테이블이 없어도 뷰를 생성 가능
create or replace force view emp_chk
as
select * from employees
where deptno=10;

-- with check option : 뷰를 생성할때 제약조건을 부여
-- 뷰 생성시 부여된 조건을 뷰의 결과가 계속 유지되도록 하겠다.
create or replace view emp_chk1
as
select e.empno, e.ename, d.dname, d.deptno
from emp e, dept d
where e.deptno = d.deptno and e.deptno=30
with check option constraint emp_v_chk1;

select * from user_constraints;
select * from emp_chk1;

-- with check option을 가진 뷰에 변경이 일어나게 되므로 수행 안됨
--update emp_chk1 set deptno=20 where deptno=30;
--update emp_chk1 set deptno=30 where deptno=20;

-- 읽기 전용 뷰
create or replace view emp_chk2
as
select e.empno, e.ename, d.dname, d.deptno
from emp e, dept d
where e.deptno = d.deptno and e.deptno=30
with read only;

-- update emp_chk2 set deptno=20 where deptno=30;
-- delete from emp_chk2;

-- 뷰 변경 : 없음 => create or replace를 통해 재생성

-- 뷰 제거
drop view emp_chk2;

-- inline view (인라인뷰:from절내에 있는 서브쿼리)
select a.empno, a.ename, a.sal, a.hiredate
from emp a,  (select deptno, max(hiredate) maxdate
              from emp
              group by deptno) b
where a.deptno = b.deptno;

-- top-n query
select rownum, a.empno, a.ename, a.sal, a.hiredate
from emp a,  (select rownum rn, deptno, hiredate from emp) b
where a.deptno = b.deptno and b.rn<5;

--------------------------------------------
-- sequence
--------------------------------------------
-- 연속적인 일련번호 생성
create table seq_test (
seq number,
name varchar2(20)
);
-- 시퀀스 생성
create sequence seq_test_seq
increment by 1
start with 1000
maxvalue 10000
nocache
nocycle;
-- 시퀀스 확인
select * from user_sequences;
-- 시퀀스 사용
insert into seq_test(seq,name)
values (seq_test_seq.nextval,'홍길동');
select * from seq_test;
-- 시퀀스 현재값
select seq_test_seq.currval from dual;
-- 시퀀스 제거
drop sequence seq_test_seq;

-------------------------------------
-- synonym
-------------------------------------
-- 객체의 이름이 길때 줄여쓰기 위해서
rename emp to employees;
select * from tab;
-- 시노님 생성
create public synonym emp for employees;
-- 시노님 확인

-- 시노님 제거
drop public synonym emp;

------------------------------------------
-- 사용자 관리
------------------------------------------
-- 사용자 생성
create user hong identified by pass;
-- 권한 부여
-- 접속, 자원사용 role(권한의 모음)을 hong에게 부여
grant connect,resource to hong;
-- dba롤 부여
grant dba to hong;
-- 전체사용자에게 권한 부여
grant connect,resource,dba to public;
-- 권한 제거
revoke dba from hong;
-- with admin option : 부여받은 권한을 부여할 수 있는 옵션
-- sys
grant create session to scott with admin option;
-- scott
grant create session to hong;
-- 객체 권한
rename employees to emp;
grant select,insert,update,delete on emp to hong;
revoke insert,update,delete on emp from hong;
-- role(롤)
create role conn;

---------------------------------------
-- join
---------------------------------------

-- 1. cross join (cartesion product)
-- 두 테이블에서 가능한 모든 행의 조합을 생성
select count(*) from emp;
select count(*) from dept;
select empno, ename
from emp cross join dept;

-- 2. inner join (natural join, equi join)
-- cross join의 결과 중 조인조건에 맞는 행들을 추출
select e.empno, e.ename, d.dname
from emp e, dept d
where e.deptno = d.deptno;

-- 3. outter join
-- cross join의 결과 중 조인조건에 맞는 행들을 추출하고
-- 조인조건에 맞지 않는 행들도 추출
create table t1 (no number,name char(3));
create table t2 (no number,name char(3));
insert into t1 values (10,'AAA'); insert into t1 values (20,'BBB');
insert into t2 values (10,'CCC'); insert into t2 values (30,'DDD');
select * from t1; select * from t2;
-- left outer join
select t1.no, t1.name, t2.no, t2.name
from t1 left outer join t2
on t1.no = t2.no;
-- right outer join
select t1.no, t1.name, t2.no, t2.name
from t1 right outer join t2
on t1.no = t2.no;
-- full outer join
select t1.no, t1.name, t2.no, t2.name
from t1 full outer join t2
on t1.no = t2.no;

-- subquery
-- =, >, < 등의 비교연산일 경우는 서브쿼리의 결과가 한 개 나와야 함
select * from emp where job = (select job from emp where empno=7900);
-- 서브쿼리의 where절에는 그룹함수를 사용할 수 없습니다.
--select ename, sal
--from emp
--where sal = (select sal from emp where sal>avg(sal));

select e.ename,e.sal,e.deptno,d.dname
from emp e, dept d
where e.sal in (select max(sal) from emp group by deptno)
and e.deptno = d.deptno;

-- 직업이 MANAGER인 사람들과 같은 봉급을 받는 사원
select empno, ename, job, sal from emp
where sal = any (select sal from emp where job='MANAGER');

-- 직업이 MANAGER인 사람들의 최소봉급보다 작은 봉급을 받는 사원
select empno, ename, job, sal from emp
where sal < all (select sal from emp where job='MANAGER');

-- 서브쿼리의 결과가 존재하는지
select dname, deptno from dept
where exists (select * from emp where emp.deptno=10);


'ORACLE' 카테고리의 다른 글

Oracle 10g 의 휴지통 기능  (0) 2009.11.11
프로시져, 트리거의 이해-2009/02/20  (0) 2009.11.11
PL/SQL의 이해-2009/02/19  (0) 2009.11.11
내장함수의 이해-2009/02/18  (0) 2009.11.11
쿼리 및 집합의 이해-2009/02/16  (0) 2009.11.11
Posted by Tiwaz
ORACLE2009. 11. 11. 21:19

-----------------------------
-- hr
-----------------------------

-- 테이블 생성
create table temp_emp (
id number not null,
name varchar2(12),
primary key (id)
);

-- 테이블 검색
select * from tab where tname='TEMP_EMP';

-- 테이블 구조보기
desc temp_emp;

-- commit/rollback
insert into temp_emp(id, name) values(1,'홍길동');
select name from temp_emp where id=1;
commit;
update temp_emp set name='홍인영' where id=1;
insert into temp_emp(id, name) values(2,'홍판서');
select * from temp_emp;
rollback;
commit;
select name from temp_emp where id=1;
delete temp_emp;
rollback;
select name from temp_emp where id=1;

select * from temp_emp;
update temp_emp set name='홍만석' where id=1;
savepoint a;
insert into temp_emp(id,name) values(3,'강감찬');
savepoint b;
delete from temp_emp;
rollback to savepoint a;


----------------------------
-- sys
----------------------------
-- 예약어
select keyword from v$reserved_words order by keyword;


----------------------------
-- hr
----------------------------
select * from departments;


----------------------------
-- scott
----------------------------

-- *** select

-- scott의 모든 테이블
select * from tab;
-- emp테이블의 모든 컬럼 조회
select * from emp;
-- emp테이블의 구조
desc emp;
-- emp테이블의 empno, ename 컬럼 조회
select empno, ename from emp;
-- emp테이블에 있는 job의 종류 조회
select distinct job from emp;
select job from emp;
-- emp테이블에 있는 모든 job
select all job from emp;
-- sal에 대해 정렬
select * from emp order by sal asc;
select * from emp order by sal;    
select * from emp order by sal desc;
-- 정렬시 null인 값은 마지막에
select * from emp order by comm;
-- 2차 정렬 (1차정렬이 완료된 후 2차정렬함)
select deptno, ename from emp order by deptno, ename;
-- alias (별칭)
select empno, sal 봉급, sal*0.1 보너스, sal+sal*0.1 총수령액 from emp;
-- emp테이블에서 deptno가 10
select empno, ename, deptno from emp
where deptno=10;
-- 현재 오라클이 인식하는 날짜 형식 알아내기
select value from nls_session_parameters
where parameter='NLS_DATE_FORMAT';
-- 사원들의 입사일
select hiredate from emp;
-- 1983년 이전에 입사한 사원들의 데이터
select * from emp where hiredate<'83/01/01';
-- 조건연산
select * from emp where deptno=10 and sal<3000;
-- not in 연산 (job이 SALESMAN이 아닌 데이터)
select * from emp where job not in 'SALESMAN';
-- in 연산 (job이 CLERK, MANAGER인 데이터)
select * from emp where job in ('CLERK','MANAGER');
select * from emp where job='CLERK' or job='MANAGER';
-- like 연산
-- ename에 M이 포함된 모든 데이터
select * from emp where ename like '%M%';
-- ename이 M으로 시작하는 모든 데이터
select * from emp where ename like 'M%';
-- ename이 M으로 끝나는 모든 데이터
select * from emp where ename like '%M';
-- 한글자는 _ (_자체를 표시하려면 \_)
select * from emp where ename like '_____';
-- between a and b (a, b를 포함해서 그 사이)
select empno, deptno from emp where deptno between 10 and 20;
select empno, deptno from emp where deptno>=10 and deptno<=20;
select * from emp where ename between 'A' AND 'K';
select * from emp where hiredate between '81/01/01' and '83/05/01';
-- null : 데이터 없음
select * from emp where comm is null;
select * from emp where comm is not null;
-- (X) select * from emp where comm=null;
-- 문자열 접합
select ename||'의 1년 연봉은'||sal||' 입니다!' as 연봉 from emp;
-- union (합집합)
select empno, ename from emp
union
select deptno, dname from dept;
-- union all (합집합 + 교집합)
select empno, ename from emp
union all
select deptno, dname from dept;
-- intersect (교집합)
select empno, ename from emp
intersect
select deptno, dname from dept;
-- minus (차집합)
select empno, ename from emp
minus
select deptno, dname from dept;
select deptno, dname from dept
minus
select empno, ename from emp;
-- projection : 열(컬럼) 추출
-- selection : 행(로) 추출

-- *** DML (Data Manipulation Language) - insert, update, delete
create table emp_dml(
sid number primary key,
name varchar2(12)
);
create table emp_dml2(
sid number primary key,
name varchar2(12)
);
-- insert
insert into emp_dml values (1111,'홍길동');
select * from emp_dml;
insert into emp_dml(sid, name) values(2222,'이순신');
-- null허용컬럼은 insert하지 않으면 null값 insert됨
insert into emp_dml(sid) values(3333);
-- subquery를 이용한 데이터 insert
insert into emp_dml2(sid, name) values(4444,'장화');
insert into emp_dml2(sid, name) values(5555,'홍련');
insert into emp_dml select * from emp_dml2;
-- update
update emp_dml set name='이순삼' where sid=2222;
-- subquery를 이용한 update
update emp_dml set name='박순삼'
where sid=(select sid from emp_dml2 where name='장화');
-- delete
delete from emp_dml where sid=1111;
delete from emp_dml where sid=(select sid from emp_dml2 where name='장화');
commit;


Posted by Tiwaz