블로그 이미지
좋은느낌/원철
이것저것 필요한 것을 모아보렵니다.. 방문해 주셔서 감사합니다..

calendar

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

Notice

    'Oracle'에 해당되는 글 7

    1. 2009.05.21 리눅스 환경에서 Oracle JDBC설정
    2. 2009.05.19 Listener
    3. 2009.05.13 like 대신 instr
    4. 2009.05.13 [ORACLE]SGA
    5. 2009.05.13 [ORACLE]WITH 구문 사용하기
    6. 2009.04.24 Oracle 분석함수
    7. 2008.08.25 oracle " select sysdate from dual" db2에서는?
    2009. 5. 21. 20:01 개발/Oracle

    리눅스 환경에서 Oracle JDBC설정

     

    글쓴이: 굿스피드 (2003년 09월 04일 오전 11:44) 읽은수: 495

    JDBC는 자바에서 SQL문을 실행하기 위한 자바 API이다. "Java DataBase Connectivity"의 약자로 간주되기도 하지만 사실상은 상표이름이다. JDBC는 자바로 작성되어진 클래스와 인터페이스들로 구성되어있다. 툴/데이터베이스 개발자들을 위한 표준 API를 제공하고 pure 자바 API를 사용하여 데이터베이스 어플리케이션을 만들게 해준다.

    JDBC를 사용하면, 어떠한 관계 데이터베이스(relational database)로도 SQL문을 전송하기 쉽다. 즉, JDBC API를 사용하면 Sybase, Oracle, Informix에 접근하는 프로그램을 따로 만들 필요가 없다. 단지 하나의 프로그램을 작성하고 그 프로그램에서 SQL 문을 적당한 데이터베이스에 전송할 수 있다. 또한 어플리케이션을 자바로 작성한다면, 어플리케이션을 플랫폼에 따라 다르게 작성하지 않아도 되기 때문에 자바와 JDBC의 결합은 하나의 프로그램이 어디에서나 동작할 수 있게 해준다.

    +환경 설정

    리눅스 환경에서 oracle jdbc를 구동하기 위해서는 먼저 oracle jdbc드라이버가 있어야 된다. 오라클 설치시 기본 권정사항으로 설치했다면 이미 jdbc드라이버가 들어있다. 만약 없다면 아래 링크에서 버전별로 자신의 오라클에 맞는 드라이버를 다운받기 바란다.

    Oracle JDBC Download

    필자는 오라클 8.1.7을 설치했다. 기본 권장 사항 설치를 했을 경우 JDBC드라이버가 지원이 되었었다. 기본 권장 사항 설치시 jdbc드라이버의 경로는 $ORACLE_HOME/product/8.1.7/jdbc/lib이다.

    lib폴더 아래 보면 classes111.zip(9i는 classes12.zip)화일이 있을것이다. jdbc드라이버가 있는것이 확인됐다면 이제 드라이버 환경 설정을 해보자

    [root@localhost]#
    [root@localhost]# unzip classes111.zip
    [root@localhost]# ls
    javax	oracle
    

    먼저 classes111.zip의 압축을 풀어보면 javax oracle폴더가 보일것이다. 이것일 jar로 압축해서 사용을 할 것이다.

    [root@localhost]#
    [root@localhost]# jar cvf classes111.jar javax/ oracle/
    

    위와 같이 jar로 압축을 하면 classes111.jar화일이 생성이 된다. 이제 CLASSPATH설정을 해보자.

    [root@localhost]#
    [root@localhost]# vi /etc/profile
    export CLASSPATH="$CLASSPATH:/oracle/product/8.1.7/jdbc/lib/classes111.jar"
    
    [root@localhost]# set | grep CLASSPATH
    CLASSPATH=.:/usr/local/JSDK/lib/jsdk.tar:/usr/local/tomcat/common/lib/servlet.jar:
    /oracle/product/8.1.7/jdbc/lib/classes111.jar
    

    위와 같이 classes111.jar이 나와야 정상이다. 일단 oracle jdbc가 제대로 설정이 되었나 테스트를 해보자.

    +Oracle JDBC 테스트 #1

    먼저 드라이버가 제대로 설정이 되었는지 테스트 해보자. 우선 아래와 같이 입력한다. JAVA에서 오라클 드라이버의 로딩을 확인해 볼 수 있다.

    [root@localhost]#
    [root@localhost]# javap oracle.jdbc.driver.OracleDriver
    Compiled from OracleDriver.java
    public class oracle.jdbc.driver.OracleDriver extends java.lang.Object 
    implements java.sql.Driver
        /* ACC_SUPER bit NOT set */
    {
        public static final char slash_character;
        public static final char at_sign_character;
        static final java.lang.String oracle_string;
        static final java.lang.String user_string;
        static final java.lang.String password_string;
        static final java.lang.String database_string;
        static final java.lang.String server_string;
        static final java.lang.String access_string;
        public static final java.lang.String protocol_string;
        public static final java.lang.String dll_string;
        --------------중간 생략-----------------------
        public int getMajorVersion();
        public int getMinorVersion();
        public boolean jdbcCompliant();
        public static java.lang.String getCompileTime();
        public oracle.jdbc.driver.OracleDriver();
        static {};
    }
    

    만약 위와 같이 안나온다면 CLASSPATH설정을 확인해 보기 바란다. 설정이 제대로 안되있다면 아래와 같이 에러가 나올 것이다.

    [root@localhost]#
    [root@localhost]# javap oracle.jdbc.driver.OracleDriver 
    Class 'oracle.jdbc.driver.OracleDriver' not found
    

    이제 실제로 java와 jsp테스트를 해보자. 소스가 좀 길다. 하지만 정확한 테스트가 가능하니 꼭 테스트 해보기 바란다.

    [root@localhost]#
    import java.sql.*;
    
    public class Jdbctest {
    public static void main (String args[]) {
    try {
    /* This produces more output then suitible for this article */
    /* Uncomment the next line for more connect information */
    // DriverManager.setLogStream(System.out); 
    /*
    * Set the host port and sid below to 
    * match the entries in the listener.ora
    * Must have a SCOTT/TIGER schema
    */
    String host = "127.0.0.1"; // change,these won\'t work
    String port = "1521";
    String sid = "oracle";
    // or pass on command line all three items
    if ( args.length >= 3 ) {
    host = args[0];
    port = args[1];
    sid = args[2];
    }
    
    String s1 = "jdbc:oracle:thin:@" + 
    host + ":" +
    port + ":" +
    sid ;
    
    if ( args.length == 1 ) {
    s1 = "jdbc:oracle:oci8:@" +
    args[0];
    }
    
    
    if ( args.length == 4 ) {
    s1 = "jdbc:oracle:" + args[3] + ":@" + 
    "(description=(address=(host=" + host+
    ")(protocol=tcp)(port=" + port+ 
    "))(connect_data=(sid=" + sid +
    ")))";
    }
    
    
    System.out.println( "Connecting with: " );
    System.out.println( s1 );
    
    DriverManager.registerDriver(
    new oracle.jdbc.driver.OracleDriver());
    Connection conn = DriverManager.getConnection( s1,
    "scott",
    "tiger");
    
    DatabaseMetaData dmd = conn.getMetaData();
    System.out.println("DriverVersion: ["+
    dmd.getDriverVersion()+"]");
    System.out.println("DriverMajorVersion: ["+
    dmd.getDriverMajorVersion()+"]");
    System.out.println("DriverMinorVersion: ["+
    dmd.getDriverMinorVersion()+"]");
    System.out.println("DriverName: ["+
    dmd.getDriverName()+"]");
    
    if ( conn!=null )
    conn.close();
    System.out.println("Done.");
    
    } catch ( SQLException e ) {
    System.out.println ("\\n*** Java Stack Trace ***\\n"); 
    e.printStackTrace();
    
    System.out.println ("\\n*** SQLException caught ***\\n"); 
    while ( e != null ) {
    System.out.println ("SQLState: " + e.getSQLState ()); 
    System.out.println ("Message: " + e.getMessage ()); 
    System.out.println ("Error Code: " + e.getErrorCode ()); 
    e = e.getNextException (); 
    System.out.println (""); 
    } 
    }
    }
    }
    

    테스트는 접속 방식은 thin oci8의 두가지로 테스트를 해본다. 127.0.0.1에는 오라클 리스너에 등록되어있는 포트를 넣어주고 1521은 오라클 기본포트이다. ORCL은 오라클 SID이다. 자신에게 맞는것을 넣어주면 된다.

    [root@localhost]#
    [root@localhost]# javac Jdbctest.java
    [root@localhost]# java Jdbctest 127.0.0.1 1521 ORCL thin(or 
    oci8)
    Connecting with:
    jdbc:oracle:thin:@(description=(address=(host=127.0.0.1)(protocol=tcp)
    (port=1521))(connect_data=(sid=oracle)))
    DriverVersion: [8.1.7.1.0]
    DriverMajorVersion: [8]
    DriverMinorVersion: [1]
    DriverName: [Oracle JDBC driver]
    Done.
    

    위와 같이 나오면 연결에 성공한 것이다. 만약 안된다면 CLASSPATH를 확인하기 바란다.

    +Oracle JDBC 테스트 #3

    이제 jsp환경에서 테스트를 해보자 필자의 jsp환경은 jakarta-tomcat-4.1.18과 apache_1.3.27을 mod_jk로 연동시켰다.

    [root@localhost]#
    [root@localhost]# vi oracle.jsp
    <%@ page language="java" import="java.sql.*" 
    contentType="text/html;charset=KSC5601" %>
    <%
    Class.forName("oracle.jdbc.driver.OracleDriver");
    Connection Conn =
    DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:SID","scott","tiger");
    Statement stmt = Conn.createStatement();
    ResultSet rs = stmt.executeQuery("select * from tab");
    if (rs==null)
    {
               out.println("none");
    }
    else {
               out.println("oracle jdbc 연결 성공");
    }
    stmt.close();
    Conn.close();
    %>
    

    위와 같이 저장하고 웹브라우저로 확인해 보자. 만약 에러가 난다면 tomcat4가 jdbc드라이버를 제대로 인식을 못하는 것이다.

    +Oracle JDBC 트러블 슈팅

    tomcat 4버전부터 연동하는데 조금 어려움이 있다. 정상적으로 CLASSPATH도 잡혀있고 java와의 연동도 되지만 jsp와의 연동이 잘 안될때가 많았다. 이럴때는 다음과 같이 링크를 걸어주기 바란다.

    [root@localhost]#
    [root@localhost]# ln -s /oracle/product/8.1.7/jdbc/lib/classes111.jar \
    /usr/local/tomcat/common/lib/classes111.jar
    

    이렇게 링크를 걸어주면 tomcat환경에서 jdbc의 연동이 가능할것이다. 마지막으로 oracle과 tomcat + apache와의 연동에서 jdbc연동이 안된다면 apachectl시작 스크립트에 oracle환경 설정이 등록되어있나 확인해 보기 바란다. 물론 리스너쪽 설정도 이상이 없어야 한다.

    오라클 환경 설정은 ORACLE_HOME ORACLE_SID만 설정되어 있으면 된다.


    재 등록일 : 2003년 09월 06일 오후 09:29

     

    원문 : 나소드(http://www.nasord.com/stories.php?story=03/09/04/3444708)

    posted by 좋은느낌/원철
    2009. 5. 19. 20:04 개발/Oracle

    http://radiocom.kunsan.ac.kr
    오라클 리스너(Listener)는 네트워크를 이용하여 클라이언트에서 오라클 서버로 연결하기 위한 오라클 네트워크 관리자이다. 만약 로컬 데이터베이스가 아니고 네트워크로 연결된 원격 데이터베이스 서버에 연결하려면 원격 데이터베이스 서버는 그 리스너를 기동해야 한다. 즉, 서버가 클라이언트의 요청을 들을 수 있도록 그 리스너를 시작하는 것이다. 이러한 리스너의 시작과 종료, 또 그 상태를 확인하는 오라클 데이터베이스 관리 툴이 바로 오라클 리스너(lsnrctl)이다. 
    디폴트 리스너 이름은 LISTENER 이지만, 이 이름은 $ORACLE_HOME/network/admin/listener.ora 파일에서 리스너 이름을 변경할 수 있다.
    【예제】
    $ lsnrctl help
    The following operations are available
    An asterisk (*) denotes a modifier or extended command:
     
    start               stop                status              
    services            version             reload              
    save_config         trace               spawn               
    change_password     quit                exit                
    set*                show*               
     
    $ lsnrctl start
     
    $ lsnrctl stop
     
    $ lsnrctl status
    
    【예제】
    $ ls -l network/admin/listener.ora
    -rw-r--r--   1 oracle   oinstall     599 Jan  7 13:15 network/admin/listener.ora
    $ cat network/admin/listener.ora
    # listener.ora Network Configuration File: /export/home0/oracle/app/oracle/product/10.2.1/network/admin/listener.ora
    # Generated by Oracle configuration tools.
     
    SID_LIST_LISTENER =
      (SID_LIST =
        (SID_DESC =
          (SID_NAME = PLSExtProc)
          (ORACLE_HOME = /export/home0/oracle/app/oracle/product/10.2.1)
          (PROGRAM = extproc)
        )
      )
     
    LISTENER =
      (DESCRIPTION_LIST =
        (DESCRIPTION =
          (ADDRESS_LIST =
            (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC))
          )
          (ADDRESS_LIST =
            (ADDRESS = (PROTOCOL = TCP)(HOST = jinpo.kunsan.ac.kr)(PORT = 1521))
          )
        )
      )
     
    $ 
    
    또 다른 방법으로 오라클 리스너는 오라클 홈의 bin 디렉토리에 위치하며 리스너를 실행하면, 리슨너 프롬프트인 LSNRCTL>이 출력된다. 이때 도움말이 필요하다면 HELP를 입력하여 도움을 받을 수 있다. 이러한 오라클 리스너의 명령어 중 START는 오라클 리스너를 시작하고, STOP는 오라클 리스너를 종료하는 명령어이다. STATUS는 시작된 오라클 리스너의 상태를 확인하는 명령어이며, SERVICES는 현재 시작된 서비스의 수를 출력하는 명령어이다.
    【예제】
    $ lsnrctl
    LSNRCTL for Solaris: Version 10.2.0.1.0 - Production on 02-SEP-2007 15:47:03
     
    Copyright (c) 1991, 2005, Oracle.  All rights reserved.
     
    Welcome to LSNRCTL, type "help" for information.
     
    LSNRCTL> help
    The following operations are available
    An asterisk (*) denotes a modifier or extended command:
    
    start               stop                status
    services            version             reload
    save_config         trace               spawn
    dbsnmp_start        dbsnmp_stop         dbsnmp_status
    change_password     debug               test
    quit                exit                set*
    show*
    
    오라클 리스너 명령어의 세부 사항은 다음과 같다.
    
    start [listener_name]start listener
    stop [listener_name]stop listener
    status [listener_name]get the status of listener
    service [listener_name]get the service information of the listener
    version [listener_name]get the version information of the listener
    reload [listener_name]reload the parameter files and SIDs
    save_config [listener_name]saves configuration changes to parameter file
    trace OFF | USER | ADMIN [listener_name]set tracing to the specified level
    spawn [listener_name] spawn_alias
    [(ARGUMENTS='arg0, arg1,...')]
    change_password [listener_name]changes the password of the listener
    quit | exitexit LSNRCTL
    오라클 리스너 명령어 중에서 set과 show 명령어의 쓰임새는 다음과 같다. 【예제】 LSNRCTL> help set The following operations are available after set An asterisk (*) denotes a modifier or extended command: password rawmode displaymode trc_file trc_directory trc_level log_file log_directory log_status current_listener connect_timeout startup_waittime use_plugandplay direct_handoff save_config_on_stop LSNRCTL> help show The following operations are available after show An asterisk (*) denotes a modifier or extended command: rawmode displaymode trc_file trc_directory trc_level log_file log_directory log_status current_listener connect_timeout startup_waittime snmp_visible use_plugandplay direct_handoff save_config_on_stop LSNRCTL>
    posted by 좋은느낌/원철
    2009. 5. 13. 17:21 개발/Oracle
    instr(object_name,'abcd')>0

    where 절 밑에  object_name like '%abcd%' 로 검색하는 것보다 

    instr(object_name,'abcd') > 0 로 검색하면 더 빠르다..
    posted by 좋은느낌/원철
    2009. 5. 13. 11:08 개발/Oracle
    SGA - System Global Area

    오라클이 사용하는 글로벌 메모리영역
    쿼리가 발생하면 이 영역에 해당 데이터가 있는지 확인하고 있으면 이 영역에서 읽어간다..
    존재하지 않으면 디스크에서 읽어서 SGA에다가 옮긴 후 SGA에 있는 데이터를 읽어간다..


    System Global Area (SGA) - Overview

    SGA refers to a Shared Global Area. As the term global implies, this area is accessible to all Oracle processes and users. Each instance will have its own SGA. Oracle processes and users must share large amounts of data. If all of the processes had to get the data from the disk, the IO load would soon render response times that would be totally unacceptable. To prevent this, Oracle uses Global Memory areas, that is, CPU memory. This memory is dedicated to use for Oracle alone. The SGA contains data buffer areas, redo log buffers and the shared pool (context areas). Each area is important to the database overall performance. On Oracle8 an additional area the large pool is also configured.

    The Shared pool context areas and Database buffers provide immediate access to data that has been pre-read from either the Data Dictionary tables or the data tables. The Oracle kernel process uses an LRU (Least Recently Used) algorithm to write data back to the disks. Data is never altered on the disks directly, but is altered in memory first.

    The redo buffers contain row change information, transaction commit history and checkpoint history. This data is written into the Redo logs and eventually to the Archive logs. A commit will force a disk write as will the filling of a redo log buffer or the reaching of a pre-defined checkpoint.

    The queue and request areas store data that is being transferred between processes such as servers and other Oracle processes. The shared SQL area stores all SQL statements in a parsed form. When a user or process issues a SQL command, the shared SQL area is checked to see if the command already exists in parsed form, if it does, this shared version is used. If the multi-threaded server option is utilized, some of the user process global area is also placed in the shared pool.

    Large Pool

    Oracle8 added an optional structure called the large pool. The large pool area is used for two main purposes:

    • Contains the User Global Area (UGA) when sessions are connected using MTS
       
    • Buffers for sequential file I/O

    Before Oracle8, Oracle stored MTS user connection information in the UGA structure of the shared pool. As the number of users would increase, it was possible for the SGA to run out of space. This additional memory requirement imposed by the use of MTS would reduce the shared pool memory available for the data dictionary cache and the library cache. Oracle now uses the large pool for the session's UGA if the DBA has configured it. The large pool is protected by the shared pool latch and does not use any LRU (least recently used) algorithm to manage space. Therefore, memory must be allocated and freed by each session. An ORA-4031 message will occur if the large pool runs out of memory. You can see the space usage of the large pool by querying the V$SGASTAT view.

    Another use of the large pool is as a memory buffering area for slaved DB writers. You use the writers to attempt to mimic asynchronous I/O on various systems that do not provide this feature. Check your system's specific documentation to determine if you might benefit from multiple DB writers.

    To configure the large pool in the init.ora, use the LARGE_POOL_SIZE and LARGE_POOL_MIN_ALLOC parameters. The values can be expressed in kilobytes (KB) or megabytes (MB). Keep in mind that in allocating these structures, you are allocating additional memory to the SGA. Be careful that you do not allocate the large pool so that memory starts paging out to disk, because this can have serious performance impacts.

    SGA Structure

    The SGA is divided into the following sections:

    The DC_ parameters are internally controlled and the DBA cannot control how the cache is partitioned. The cache size is determined empirically from the SHARED_POOL_SIZE parameter.

    The Shared pool is a shared resource area that stores the cache information and the parsed images of SQL and PL/SQL procedures, packages and triggers. The cache area can be monitored and if poor hit ratio statistics are shown, increasing the init.ora SHARED_POOL_SIZE parameter will help reduce it. In addition the view V$LIBRARYCACHE helps to monitor the parsed images.

    Multiple Buffer Pools

    The way objects use blocks in the SGA depends on the nature of the object (table, index, and so forth) and the way the object is used (for example, an object may be a small, static, but constantly used lookup table, or a large, static, but rarely used data warehouse table). The different usage characteristics of these objects often demand different types of storage. Some objects should be kept in memory as long as possible and others should be cleared out of memory soon after use. To deal with these types of situations, Oracle8 provides a method of allowing more granular control over the SGA storage of database blocks and how long blocks are maintained in memory. Oracle8 provides three pools for database data block storage:

    • Default buffer cache
       
    • KEEP buffer pool
       
    • RECYCLE buffer pool

    Each of these pools allows you to assign specific database objects to them and to retain the blocks from those objects using different retention criteria. The KEEP buffer pool and the RECYCLE buffer pool segment memory from the default buffer pool, so be careful that you do not leave the default buffer pool short of memory. DBAs may use the V$BUFFER_POOL view to monitor the various buffer pool settings currently in use.

    The Default Buffer Pool

    The default buffer pool (still referred to as the database buffer cache) is always allocated in an Oracle database. To allocate memory to the default buffer pool, set the number of database buffer blocks you want the cache to be and do so by setting the DB_BLOCK_BUFFERS setting in the init.ora parameter file. The total size of this cache then is calculated as DB_BLOCK_BUFFERS * DB_BLOCK_SIZE. The LRU algorithm manages the data blocks in the default buffer pool.

    The KEEP Buffer Pool

    A CACHE option is available on database tables. This option causes database blocks that are read in from a table during a full table scan to be put onto the MRU (most recently used) end of the LRU (least recently used) list, as opposed to the LRU end. Thus, the data blocks associated with that table remain in the database buffer cache for a longer period of time before being aged out. The idea is to allow for as close to a 100 percent cache hit ratio as possible on these often-hit, smaller tables. The KEEP buffer pool gives you a dedicated segment of database buffer cache memory in which to load the blocks of these tables. Typically, these are smaller tables, such as lookup tables.

    You can set the BUFFER_POOL_KEEP parameter in init.ora to reserve part of the database buffer cache for pinned data blocks. Once the KEEP buffer pool is created, you can assign objects to this pool, and if the pool is sized properly, the data blocks from these objects will remain in memory. You must exercise caution when setting up the KEEP buffer pool. Ensure that you allocate only enough memory to store the blocks you wish kept in the buffer pool, and yet not over-allocate to the pool memory that will go unused. You determine how much memory to allocate to the pool by adding up the sizes of all the objects you intend to assign to the pool. Keep in mind that as you allocate memory to the pool, you reduce the amount of memory available in the database buffer cache to the default pool. If you undersize the pool, objects will be aged out using the LRU algorithm, as with the default buffer pool. An example of assigning a table to the KEEP buffer pool is shown below.

    CREATE TABLE small_table
     (pk_id NUMBER NOT NULL PRIMARY KEY,
     table_info VARCHAR2 NOT NULL)
    STORAGE (INITIAL 1M, NEXT 1M, BUFFER_POOL KEEP)

    The RECYCLE Buffer Pool

    The RECYCLE buffer pool's purpose is to store memory blocks that are not likely to be reused again soon. In the case of very large objects, access to individual blocks may be very random and scattered. In these circumstances, you may wish to assign such objects to the RECYCLE buffer pool.

    It is important not to size the RECYCLE buffer pool too small. Doing so may cause blocks to age out of the pool before an application or SQL statement uses them completely. To configure the RECYCLE pool, set the BUFFER_POOL_RECYCLE parameter in the init.ora file.

    If the block is aged out before the transaction is done with it, it needs to be re-read, causing more I/O. You can determine if this is happening by using one of the trace methods (for example, turning on trace and using tkprof to format the output trace file). To do so, compare disk accesses that occur in the default pool to disk access occurring in the RECYCLE buffer pool. In both cases, disk accesses should be the same. If the statement that ran and that was using the RECYCLE buffer pool has more disk accesses, you may conclude that the pool is too small. Another method of monitoring the pool is to monitor the free buffer waits and log file sync statistics. If either of these starts to grow after you allocate the RECYCLE buffer pool, it may mean that you have not allocated enough memory to the pool.

    The following is a guide for determining which objects should fit in the RECYCLE buffer pool:

    • A good candidate for a segment to put into the RECYCLE buffer pool is one that is at least twice the size of the default buffer pool and has incurred at least a few percent of the total I/Os in the system. 
       
    • A good candidate for a segment to put into the KEEP pool is one that is smaller than 10 percent of the size of the default buffer pool and has incurred at least 1 percent of the total I/Os in the system.
       
    • Calculate the ratio of blocks for a segment of the object in question that is used frequently to those used rarely. For that object, count the number of blocks that exist in the hot half of the cache (the MRU end) to the number of blocks in the cold half (the LRU end). If the ratio for a segment is close to 1, the segment may be a good candidate for the RECYCLE cache. If the ratio is high (perhaps 3), the segment might be a good candidate for the KEEP cache.

    An example of assigning a table to the RECYCLE buffer pool is shown below.

    CREATE TABLE small_table
     (pk_id NUMBER NOT NULL PRIMARY KEY,
     table_info VARCHAR2 NOT NULL)
    STORAGE (INITIAL 1M, NEXT 1M, BUFFER_POOL RECYCLE)

    SGA Fixed and Variable Portions

    The fixed portion of the SGA refers to the area unaffected by the INIT{sid}.ORA parameter values. The fixed portion may however vary between Oracle versions because of additional INIT{sid}.ORA parameters in the newer versions. This size can also vary between different Unix platforms due to different alignment Procedures. The fixed component of SGA is not tunable.

    The variable portion of the SGA consists of arrays of variables that are allocated based upon the INIT.ORA parameters.

    The list below states the impact that different INIT.ORA parameters have on the variable portion of the SGA:

    • DB_FILES - The lower the value of this parameter, the less the space needed. If this is set to 10 the gain in the space is about 6240 Bytes.
       
    • DB_FILE_MULTIBLOCK_READ_COUNT - The higher the value for this parameter, the less space needed.
       
    • All Dictionary cache parameters ( i.e. all DC_XXX Paratamers ) - Space needed for additional values of these parameters is not too high.
       
    • DDL_LOCKS - Space needed for additional value of 100 for this parameter is ~ 5.0k.
       
    • DML_LOCKS - Space needed for additional value of 100 for this parameter is ~ 9.76K.
       
    • ENQUEUE_RESOURCES - Space needed for additional value of 10 for this parameter is ~ 0.7k.
       
    • PROCESSES - Space needed for additional value of 10 for this parameter is ~ 19.5k.
       
    • ROW_CACHE_ENQUEUES - Space needed for additional value of 100 for this parameter is ~ 3.5K
       
    • SEQUENCE_CACHE_ENTRIES - Space needed for additional value of 10 for this parameter is ~ 1.17k
       
    • SEQUENCE_CACHE_HASH_BUCKETS - Space needed for additional value of 10 for this parameter is ~ 0.08k
       
    • SESSIONS - Space needed for additional value of 10 for this parameter is ~ 5.3K
       
    • TRANSACTIONS - Space needed for additional value of 10 for this parameter is ~ 0.85K.
       
    • TRANSACTIONS_PER_ROLLBACK_SEGMENT - More space is needed for lower values of this parameter

    Data Block Buffers

    The data block buffers are a cache in the SGA used to hold the data blocks read from the data segments in the database (e.g., tables, indexes, and clusters). The size of the data block buffer cache is determined by the INIT.ORA parameter DB_BLOCK_BUFFERS.

    The data block buffer cache is fixed in size and is usually smaller than the space used by database segments. This means it cannot hold all of the database's segments in memory at one time. The SGA retains the information stored in its cache buffers in accordance with the Least Recently Used (LRU) algorithm. The LRU algorithm determines what objects haven't been used for a given period of time and allows those objects to be over-written as needed to make way for additional data.

    Dictionary Cache

    The dictionary cache is used to store information about the database objects. This includes:

    • User account data
       
    • Datafile names
       
    • Segment names
       
    • Extent locations
       
    • Table descriptions
       
    • Privileges

    When any of this information is needed by the database, that data dictionary tables are read and the data is returned and stored in the SGA (in the dictionary cache).

    The dictionary cache is also managed using the LRU algorithm. The dictionary cache is part of the shared SQL Pool and is managed internally by the database. The size of the cache is set via the init.ora SHARED_POOL_SIZE parameter.

    Care should be given not to define the dictionary cache too small. This will result in the database repeatedly querying the data dictionary tables for the information it requires. These are known as recursive hits and are much slower than queries against the dictionary cache in memory.

    Redo Log Buffer

    Redo log files contain entries that describe the changes that have been made to the database. These entries are used in roll-forward operations during a database recovery. Before the entries are written to the online redo log files, they are first cached in the SGA. This area of the SGA is known as the redo log buffer.

    The size of the redo log buffer is set via the LOG_BUFFER parameter in the init.ora file.

    Click Here for additional information on Redo Log configuration.

    Shared SQL Pool

    The shared SQL pool is used to store the Dictionary Cache as well as information about SQL statements that are being run against the database. This shared SQL information consists of the execution plan and parse tree for the SQL statement. This enables subsequent (identical) SQL statements to reuse the parse information to accelerate its execution.

    SGA Size

    The size of the SGA is controlled by buffer sizes, and the buffer sizes are controlled by the database block size, which is specified at database creation and cannot be changed without rebuilding the database. This usually defaults to 2 KB. We usually suggest at least 4KB, and in most cases 8 KB works best. If in doubt, set the block size to the largest supported on your system.

    The five major components of the SGA are the database buffers, log buffers, large pool, Java pool, and the shared pool The SGA also contains the redo log buffers. The ideal situation would be to size the SGA to hold the entire database in memory. For small systems, this may be a real situation; for most, it is not feasible. Therefore, you must decide how much to allocate. Many times, especially for development databases, this will be a rough guess. For systems already designed with detailed data storage estimates, it may be better defined. A general rule of thumb for a pure Oracle system (no other applications) is 50 percent to 60 percent of available RAM for your SGA. Note that for small databases this may be overkill. In general, we have found that sizing the SGA data block buffers (the product of DB_BLOCK_SIZE and DB_BLOCK_BUFFERS) to 1/50 to 1/100 of the total physical size of the database is a good starting point. Under Oracle8i, new default sizes in the supplied sample initialization file are more realistic, but in general will still be too small for most production databases, so use them with caution.

    Oracle provides tools to analyze buffer performance. Unfortunately, they can only be used once a system is operating and running under a normal load.

    If you have no idea whatsoever, make the buffer area at least 60 to 100 MB or so (you will usually outgrow the Oracle default rather quickly) for a database that is near 1 gigabyte in total physical size, and up to 400 MB for one that is around 20 gigabytes in size. For databases smaller than 1 gigabyte physical size, the Oracle defaults may be usable. Make the shared pool at least 20 to 40 MB (not the 9 MB it will default to).

    If you overspecify the shared memory size on NT or Open-VMS you may get into a situation known as swapping. This is where all or part of your application is swapped out to disk because physical memory just isn't large enough to hold it all. Needless to say, this has a very negative impact on performance. Usually overspecification of the SGA on UNIX will lead to not being able to start the database.


    posted by 좋은느낌/원철
    2009. 5. 13. 11:07 개발/Oracle
    WITH 구문 사용하기

    WITH ALIAS_NAME
    AS   (  복잡한 SQL


        )

    SELECT * 
        FROM TABLE1 A, ALIAS_NAME B
        WHERE .....

    UNION ALL
    SELECT *
        FROM TABLE2 A, ALIAS_NAME B
        WHERE ....


    한 번 만들어 놓은 SQL구문을 재활용해서 사용할 수 있다..
    posted by 좋은느낌/원철
    2009. 4. 24. 10:20 개발/Oracle
    일단 유용한 분석함수를 보면

    select scott.emp.* 
                  , row_number() over (partition by deptno order by empno ) num
                  , rank() over (partition by deptno order by empno ) rank
                  , dense_rank() over (partition by deptno order by empno ) dense_rank
                  , lead(sal) over (partition by deptno order by empno ) next
                  , lag(sal) over (partition by deptno order by empno ) before
                  , sum(sal) over (partition by deptno order by empno ) sum

        from scott.emp

    ******************************************************************************************
    요걸 응용해서 
    세로로 되어 있는 자료를 가로로 바꿔주는 sql을 보자..

    SELECT 품목
         , MAX((CASE WHEN RK = 1 THEN 거래처 END)) AS "1등거래처"
         , MAX((CASE WHEN RK = 1 THEN 수량   END)) AS "1등수량"
         , MAX((CASE WHEN RK = 2 THEN 거래처 END)) AS "2등거래처"
         , MAX((CASE WHEN RK = 2 THEN 수량   END)) AS "2등수량"
         , MAX((CASE WHEN RK = 3 THEN 거래처 END)) AS "3등거래처"
         , MAX((CASE WHEN RK = 3 THEN 수량   END)) AS "3등수량"
      FROM (SELECT A.*
                 , ROW_NUMBER() OVER (PARTITION BY 품목 ORDER BY 수량 DESC) AS RK
              FROM 테이블명 A
           ) A
     WHERE RK <= 3
     GROUP BY 품목


    품목    1등거래처   1등수량   2등거래처   2등수량   3등업체   3등수량

    이렇게 나오게 된다..
    posted by 좋은느낌/원철
    2008. 8. 25. 17:48 Database

    select current_date from sysibm.sysdummy1;

    이렇게 해야 한단다...

    posted by 좋은느낌/원철
    prev 1 next