개인정보 문제가 대두되어서 운영이 아닌 테스트에서는 실제 이름과 주민번호를 넣지 말라는 방침이 내려왔다.

주민번호 뒷자리 7자리만 '1234567' 로 update 를 하려고 한다.

update [테이블명]
set
[주민번호컬럼명]=substr([주민번호컬럼명],1,6)  || '1234567'


Posted by 쭌쓰파파
,


## LONG TYPE을 LOB TYPE으로 CONVERSION하는 방법(TO_LOB) ##

Bulletin no 12143 참고


Oracle8 부터 LONG이나 LONG RAW Type과는 별도로 LOB Type이 추가 되었습니다.

LONG 이나 LONG RAW Type을 CLOB 또는 BLOB Type으로 변경하기 위해서는 Oracle8에서는
데이타를 다시 입력해야 했지만, 오라클 8i부터는 TO_LOB Function을 이용해서 Long Type의 Data를 LOB Type으로 쉽게 Conversion할 수 있습니다.

TO_LOB Function은 보통 CREATE TABLE .. AS SELECT .. 문장이나
INSERT INTO .. SELECT .. 문장을 이용해서 쉽게 사용 할 수 있습니다.



[예제1] LONG Type의 데이타를 CLOB Type으로 옮기는 방법
아래의 예제에서 Type만 LONG RAW와 BLOB으로로 바꾸어도 가능 합니다.


-- 마이그레이션 테스트를 위한 long컬럼을 가지는 테이블을 생성 합니다.
SQL>CREATE TABLE long_data (
c1 NUMBER,
c2 LONG);

테이블이 생성되었습니다.


-- 테이블의 확인
SQL> DESC long_data

Name Null? Type
----------- ------ ----
C1 NUMBER
C2 LONG


-- 샘플 데이터를 입력 합니다.
SQL>INSERT INTO long_data
VALUES (1, 'This is some long data to be migrated to a CLOB');
1 개의 행이 만들어졌습니다.

SQL>INSERT INTO long_data
VALUES (2, 'long컬럼을 clob으로 마이그레이션 하기 위한 테스트 데이터 입니다.');
1 개의 행이 만들어졌습니다.


-- clob로 마이그레이션 하는 테이블을 생성 합니다.
SQL>CREATE TABLE test_lobs(
c1 NUMBER,
c2 CLOB);

테이블이 생성되었습니다.


-- 테이블의 확인
SQL> DESC test_lobs
Name Null? Type
----------- -------- ----
C1 NUMBER
C2 CLOB


-- LONG타입의 데이터를 CLOB타입의 데이터로 변환
SQL>INSERT INTO test_lobs
SELECT c1, to_lob(c2)
FROM long_data;
2 개의 행이 만들어졌습니다.


-- 변환된 데이터를 확인 합니다.
SQL> SELECT c2 FROM test_lobs;

C2
-----------------------------------------------------------------
This is some long data to be migrated to a CLOB
long컬럼을 clob으로 마이그레이션 하기 위한 테스트 데이터 입니다.





[예제2] LONG Type을 CLOB Type으로 바꾸어 Table 생성하는 방법


-- 새로운 테이블을 생성하면서 기존의 LONG Type의 데이터를 CLOB Type의 데이터로 변환합니다.
SQL>CREATE TABLE clob_data
AS SELECT c1, to_lob(c2) c2
FROM long_data;
테이블이 생성되었습니다.


-- 데이터를 확인해 보세요..
SQL> SELECT c2 FROM long_data;




[예제3] LONG RAW Type을 BLOB Type으로 바꾸어 Table 생성하는 방법


-- image_data테이블에 LONG RAW컬럼이 있다고 가정을 하면은
SQL> DESC image_data
Name Null? Type
------------------------------- -------- ----
C1 NUMBER
C2 LONG RAW


-- 아래의 예제와 같이 테이블을 생성하면서 쉽게 blob Type으로 변환 할 수 있습니다.
SQL>CREATE TABLE blob_data
AS SELECT c1, to_lob(c2) c2 FROM image_data;


================================================
* 오라클 정보공유 커뮤니티 oracleclub.com
* http://www.oracleclub.com
* http://www.oramaster.net
* 운영자 : 김정식 (oramaster _at_ naver.com)
================================================
※ oracleclub 강좌를 다른 홈페이지에 퍼가실 경우에는 출처를 꼭 밝혀 주시면 고맙겠습니다.~^^

Posted by 쭌쓰파파
,

Oracle 8.1.6 에서 테스트 해 본 쿼리이다.

함수를 이용하여 항상 랜덤하게 정렬을 할 수 있다.

select  *

from table_name
where code = '01'
order by dbms_random.value
 

Oracle 내에서 생성하는 임의의 수를 바탕으로 뽑아진 데이터를 랜덤하게 정렬한다.

위의 예제는 code 가 "01" 인 데이터들을 임의의 순서로 정렬하는 예제이다.

이벤트 응모자들을 랜덤하게 당첨하는 프로그램을 궁리해보다가 사랑넷에서 찾아낸 예제.


select mod(abs(dbms_random.random),99) + 1 from dual


↑ 이건 랜덤하게 0~99까지의 숫자중 하나를 뽑아서 +1 을 하여 보여주는 예제.

Posted by 쭌쓰파파
,


오라클에서 rownum 과 index 칼럼을 사용하여
72000건 이상의 테이블에서 제일 마지막 페이지를 가져오는 쿼리


SELECT {$칼럼들} FROM
(
   SELECT ROWNUM AS RNUM, {$칼럼들} FROM
   (
      SELECT /*+ INDEX_DESC (board_description SYS_C005873) */ {$칼럼들} FROM board_description
   )
   WHERE ROWNUM <= 72220
)
WHERE RNUM > 72210  and RNUM <= 72220


index 칼럼을 이용하지 않을 때는 INDEX가 들어가는 쿼리 부분을 칼럼들을 가져오는 쿼리문으로 바꿔서 가상의 테이블을 생성.

Posted by 쭌쓰파파
,

원문 발췌 :
http://javaservice.net/~java/bbs/read.cgi?m=qna&b=qna2&c=r_p_p&n=1087876976

제목 : Re: Clob은 empty_clob()함수를 이용해 초기화 해야 합니다.
글쓴이: 이승배(telarin) 2004/06/21 06:49:20 조회수:376 줄수:8
CLOB형의 데이터들은 별도의 저장공간에 저장되기 때문에..
핸들이 좀 특이합니다.

INSERT INTO test(testcode, content) VALUES('test1', empty_clob());
또는
UPDATE test SET content = test_clob() WHERE testcode = 'test1';

이런식으로요..
제목 : Re: 오라클 Clob 타입 selec시에 데이터가 없을때는 수행되지 않게끔 하시면 됩니다.
글쓴이: 송원만(nitto182) 2004/06/22 13:02:56 조회수:1256 줄수:318
select시에 데이터가 없을때를 대비하여 아래와 같이 if문에서 Reader가 null인지 체크
하여 주시면 될것입니다.

참고로 아래소스는 ClobUtil이라는 별도의 유틸리티 클래스를 이용하고 있는 모습니다.
(특별히 이렇게 분리 시키지 않아도 되지만 많이 사용되는만큼 분리시키시는게 편리
할것입니다.)

또한 아래 참조 소스는 clob data가 여러컬럼일때 작업하는 방법도 함께 예제로 넣었습니다.
많은 참고가 되었으면 합니다.




[ClobUtil클래스 (※전체소스는 첨부파일 참조)]

public class ClobUtil{

...
    public static String getClobOutput(Reader input) throws IOException,Exception{
        return getClobOutput(input, 4096);
    }

    public static String getClobOutput(Reader input, int buffer_size) throws IOException,Exception{

        if(input != null){  // 이부분이 Reader가 null인지 체크하는 부분
            try{
                StringBuffer output = new StringBuffer();
                char[] buffer = new char[buffer_size];
                int byteRead;

                while((byteRead=input.read(buffer, 0, buffer_size)) != -1){
                    output.append(buffer, 0, byteRead);
                }
                input.close();
                return output.toString();
            }catch(Exception e){// Trap SQL and IO errors
                throw new Exception("getClobOutput() Fail !!");    // runtime 에러시 화면에 찍힘.
            }
        }else{
            return "";
        }
    }
/*
            다른방법1 (oracle 권장 (sample sorce중에서))
            // Open a stream to read Clob data
            Reader src = p_clob.getCharacterStream();

            // Holds the Clob data when the Clob stream is being read
            StringBuffer l_suggestions = new StringBuffer();

            // Read from the Clob stream and write to the stringbuffer
            int l_nchars = 0; // Number of characters read
            char[] l_buffer = new char[10];  //  Buffer holding characters being transferred

            while ((l_nchars = l_clobStream.read(l_buffer)) != -1) // Read from Clob
                l_suggestions.append(l_buffer,0,l_nchars); // Write to StringBuffer

            l_clobStream.close();  // Close the Clob input stream

*/

...

}


[특정클래스에서]

import java.sql.*;
import java.io.*;
import java.util.*;
import oracle.sql.*;                // CLOB 때문
import oracle.jdbc.driver.*;        // OracleResultSet...때문
import common.db.DBConnHandler;
import common.utils.ClobUtil;       // CLOB 때문

public class EntpDB {


    // 여러개의 clob data를 insert하는 예제
    public boolean insert(EntpRec entity) throws SQLException,IOException,Exception{

        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        StringBuffer sb = new StringBuffer(300);
        boolean rtn = false;

        try{
            db = new DBConnHandler();
            conn = db.getConnection();
            conn.setAutoCommit(false);
            sb.append(" INSERT INTO TEST_TABLE ");
            sb.append(" (id,class_code,content_1,content_2,content_3,cre_user_id,cre_dt) ");
            sb.append(" VALUES((Select NVL(MAX(id), 0)+1 id FROM TEST_TABLE),?,empty_clob(),empty_clob(),?,sysdate) ");
            pstmt = conn.prepareStatement(sb.toString());
            pstmt.setInt(1, entity.class_code);
            pstmt.setString(2, entity.cre_user_id);

            if(pstmt.executeUpdate()>0){
                pstmt.close();
                sb.setLength(0);
                sb.append(" SELECT content_1,content_2,content_3 FROM TEST_TABLE ");
                sb.append(" WHERE (id=(SELECT NVL(MAX(id), 0) id FROM TEST_TABLE)) ");
                sb.append(" FOR UPDATE");
                pstmt = conn.prepareStatement(sb.toString());
                rs = pstmt.executeQuery();

                while(rs.next()){
                    CLOB clob = ((OracleResultSet)rs).getCLOB(1);
                    Writer writer = clob.getCharacterOutputStream();
                    ClobUtil.writeClob(writer, entity.content_1);

                    clob = null;
                    writer = null;
                    clob = ((OracleResultSet)rs).getCLOB(2);
                    writer = clob.getCharacterOutputStream();
                    ClobUtil.writeClob(writer, entity.content_2);


                    clob = null;
                    writer = null;
                    clob = ((OracleResultSet)rs).getCLOB(3);
                    writer = clob.getCharacterOutputStream();
                    ClobUtil.writeClob(writer, entity.content_3);
                }
/*
                (예전에 직접처리하던방식-불편함)
                ...
                pstmt.close();
                sb.setLength(0);
                sb.append("select bd_body_1,bd_body_2 from board_table where id=? for update");
                pstmt = conn.prepareStatement(sb.toString());
                pstmt.setInt(1, boardRec.getBd_seq);
                rs = pstmt.executeQuery();

                while(rs.next()){
                    CLOB clob = ((OracleResultSet)rs).getCLOB(1);
                    Writer writer = clob.getCharacterOutputStream();
                    Reader src = new CharArrayReader((boardRec.getBd_body_1()).toCharArray());
                    char[] buffer = new char[1024];
                    int read = 0;
                    while( (read = src.read(buffer,0,1024)) != -1){
                        writer.write(buffer, 0, read); // write clob.
                    }
                    src.close();
                    writer.close();

                    clob = null;
                    writer = null;
                    clob = ((OracleResultSet)rs).getCLOB(2);
                    writer = clob.getCharacterOutputStream();
                    Reader src = new CharArrayReader((boardRec.getBd_body_2()).toCharArray());
                    char[] buffer = new char[1024];
                    int read = 0;
                    while( (read = src.read(buffer,0,1024)) != -1){
                        writer.write(buffer, 0, read); // write clob.
                    }
                    src.close();
                    writer.close();
                    ...
                }
*/

                conn.commit();
                rtn = true;

            }else{
                logs.logIt("error","insert 처리(CLOB의 내용 제외)를 하지 못하고 db 에러남.\n"+
                                   " > entity : "+entity.toString()+"\n"+
                                   " > query : "+sb.toString()+"\n");
            }
        }catch(SQLException e){
            logs.logIt("error","insert 처리를 하지 못하고 에러남.\n"+
                               " > entity : "+entity.toString()+"\n"+
                               " > query : "+sb.toString()+"\n", e);
            if(conn != null)	conn.rollback();
            throw e;
        }finally{
            conn.setAutoCommit(true);
            if(rs != null)		rs.close();
            if(pstmt != null)	pstmt.close();
            db.release();
        }
        return rtn;
    }


    // 여러개의 clob data를 select예제
    public EntpRec select(int id) throws SQLException,IOException,Exception{

        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        StringBuffer sb = new StringBuffer(1000);
        EntpRec entity = null;

        try{
            db = new DBConnHandler();
            conn = db.getConnection();
            sb.append(" SELECT id,class_code,cre_user_id,upt_user_id,to_char(cre_dt,'YYYY/MM/DD HH24:MI') cre_dt, ");
            sb.append(" to_char(upt_dt,'YYYY/MM/DD HH24:MI') upt_dt ");
            sb.append(" FROM TEST_TABLE ");
            sb.append(" WHERE (entp_id=? "+where+")");
            pstmt = conn.prepareStatement(sb.toString());
            pstmt.setInt(1, entp_id);
            rs = pstmt.executeQuery();

            if(rs.next()){
                entity = new EntpRec();
                entity.entp_id = rs.getInt("entp_id");
                entity.class_code = rs.getInt("class_code");
                entity.content_1 = ClobUtil.getClobOutput(rs.getCharacterStream("content_1"));
                entity.content_2 = ClobUtil.getClobOutput(rs.getCharacterStream("content_2"));
                entity.content_3 = ClobUtil.getClobOutput(rs.getCharacterStream("content_3"));
                entity.cre_user_id = rs.getString("cre_user_id");
                entity.upt_user_id = rs.getString("upt_user_id");
                entity.cre_dt = rs.getString("cre_dt");
                entity.upt_dt = rs.getString("upt_dt");

                Utility.fixNull(entity);
            }
        }catch(SQLException e){
            logs.logIt("error","[특정 pk에 따른 한 레코드 select하지 못하고 에러남.\n"+
                        " > id : "+id+"\n"+
                        " > query : "+sb.toString()+"\n", e);
        }finally{
            if(rs != null)        rs.close();
            if(pstmt != null)    pstmt.close();
            db.release();
        }
        return entity;
    }



    // 여러개의 clob data를 update하는 예제
    public boolean update(EntpRec entity) throws SQLException,IOException,Exception{

        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        StringBuffer sb = new StringBuffer(1000);
        boolean rtn = false;

        try{
            db = new DBConnHandler();
            conn = db.getConnection();
            conn.setAutoCommit(false);
            sb.append(" UPDATE TEST_TABLE");
            sb.append(" SET class_code=?,content_1=empty_clob(),content_2=empty_clob(),content_3=empty_clob(), ");          
            sb.append(" upt_user_id=?,upt_dt=sysdate ");
            sb.append(" WHERE (id=?)");
            pstmt = conn.prepareStatement(sb.toString());

            pstmt.setInt(1, entity.class_code);
            pstmt.setString(51, entity.upt_user_id);
            pstmt.setInt(52, entity.id);

            if(pstmt.executeUpdate()>0){
                pstmt.close();
                sb.setLength(0);
                sb.append(" SELECT content_1,content_2,content_3 FROM TEST_TABLE ");
                sb.append(" WHERE (id=?)");
                sb.append(" FOR UPDATE");
                pstmt = conn.prepareStatement(sb.toString());
                pstmt.setInt(1, entity.id);
                rs = pstmt.executeQuery();

                while(rs.next()){
                    CLOB clob = ((OracleResultSet)rs).getCLOB(1);
                    Writer writer = clob.getCharacterOutputStream();
                    ClobUtil.writeClob(writer, entity.content_1);

                    clob = null;
                    writer = null;
                    clob = ((OracleResultSet)rs).getCLOB(2);
                    writer = clob.getCharacterOutputStream();
                    ClobUtil.writeClob(writer, entity.content_2);

                    clob = null;
                    writer = null;
                    clob = ((OracleResultSet)rs).getCLOB(3);
                    writer = clob.getCharacterOutputStream();
                    ClobUtil.writeClob(writer, entity.content_3);
                }

                conn.commit();
                rtn = true;

            }else{
                logs.logIt("error","[update 처리(CLOB의 내용 제외)를 하지 못하고 db 에러남.\n"+
                            " > entity : "+entity.toString()+"\n"+
                            " > query : "+sb.toString()+"\n");
            }
        }catch(SQLException e){
            logs.logIt("error","[update 처리를 하지 못하고 에러남.\n"+
                        " > entity : "+entity.toString()+"\n"+
                        " > query : "+sb.toString()+"\n", e);
            if(conn != null)    conn.rollback();
            throw e;
        }finally{
            conn.setAutoCommit(true);
            if(rs != null)       rs.close();
            if(pstmt != null)    pstmt.close();
            db.release();
        }
        return rtn;
    }

Posted by 쭌쓰파파
,