'My Works/Oracle'에 해당되는 글 40건

  1. 2010.02.25 [펌] 오라클 Clob 타입 다루기 2
  2. 2010.02.02 [ORACLE] find pk without index
  3. 2010.01.15 [ORACLE] Oracle Session Snapper - by Tanel Poder 3
  4. 2010.01.14 [ORACLE] redo size
  5. 2010.01.13 [ORACLE 9i] invalid 상태인 procedure는 dba_procedures에서 조회불가
  6. 2009.10.28 [Oracle] Add Partition 또는 Split Partition시 ORA-00959 에러 해결방법
  7. 2009.09.14 [ORACLE] lock
  8. 2009.03.09 [ORACLE] 권한 조회 VIEW
  9. 2009.03.03 [ORACLE] dbms_metadata.get_ddl
  10. 2009.02.24 [ORACLE] To dec - http://wiki.ex-em.com/index.php/To_dec 펌

[펌] 오라클 Clob 타입 다루기

|
제목 : 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;
    }
원문 발췌 :
http://javaservice.net/~java/bbs/read.cgi?m=qna&b=qna2&c=r_p_p&n=1087876976

[펌] http://www.rainny.pe.kr/27
And

[ORACLE] find pk without index

|
---------------------------------------------------------------------------
-- title : find pk without index
-- author : proud
-- discription : find pk without (unique) index - drop and readd
-- usage : @find_pk_without_idx
-- created : 2010.02.02
-- update date:
---------------------------------------------------------------------------

set serveroutput on

drop table result_pk_without_idx;

create table result_pk_without_idx
(
 script_text varchar2(4000)
)
nologging
compress
;

declare
v_drop_sql varchar2(4000);
v_add_sql varchar2(4000);
v_own varchar2(4000);
v_tab varchar2(4000);
v_con varchar2(4000);
v_idx varchar2(4000);
v_col varchar2(4000);
v_cnt pls_integer;

begin

dbms_output.enable(9999999);

for i in (
         select a.owner
               ,a.table_name
               ,a.constraint_name
               ,a.index_name
           from dba_constraints a
               ,dba_indexes b
          where a.index_name = b.index_name(+)
            and a.constraint_type = 'P'
            and b.index_name is null
         ) loop
v_own := i.owner;
v_tab := i.table_name;
v_con := i.constraint_name;
v_idx := i.index_name;

v_drop_sql := 'alter table '||v_own||'.'||v_tab||' drop constraint '||v_con;
v_add_sql := 'alter table '||v_own||'.'||v_tab||' add constraint '||v_con||' primary key (';

v_cnt := 0;

begin
for c in (
         select column_name
           from dba_cons_columns
          where owner = ''||v_own||''
            and table_name = ''||v_tab||''
          order by position
         ) loop

v_col := c.column_name;

if v_cnt > 0 then
v_add_sql := v_add_sql||','||v_col;
else
v_add_sql := v_add_sql||v_col;
end if;

v_cnt := v_cnt + 1;

end loop;
end;

v_add_sql := v_add_sql||')';

execute immediate 'insert into result_pk_without_idx values ('''||v_drop_sql||''')';
execute immediate 'insert into result_pk_without_idx values ('''||v_add_sql||''')';
execute immediate 'commit';
end loop;

dbms_output.put_line('select * from result_pk_without_idx;');
end;
/
And

[ORACLE] Oracle Session Snapper - by Tanel Poder

|
And

[ORACLE] redo size

|
-------------------------------------------------------
-- name : show_redo
-- author : Kim, jongbum aka proud
-- description : redo size by process
-- usage : @show_redo
-- tested version : oracle 9i , 10g
-------------------------------------------------------

column osuser format a20
column username format a20
column module format a50

select max(decode(a.process,b.spid,to_number(null),a.sid)) sid
      ,max(decode(a.process,b.spid,to_number(null),a.serial#)) serial#
      ,max(decode(a.process,b.spid,null,a.process)) process
      ,a.osuser
      ,a.username
      ,a.command
      ,a.pdml_enabled
      ,a.module
      ,a.status
      ,decode(a.sql_hash_value,0,a.prev_hash_value,a.sql_hash_value) sql_hash_value
      ,sum(c.value) redo_size
  from v$session a
      ,v$process b
      ,v$sesstat c
      ,v$statname d
 where a.paddr = b.addr
   and a.sid = c.sid
   and c.statistic# = d.statistic#
   and d.name = 'redo size'
 group by a.osuser
         ,a.username
         ,a.command
         ,a.pdml_enabled
         ,a.module
         ,a.status
         ,decode(a.sql_hash_value,0,a.prev_hash_value,a.sql_hash_value)
/
And

[ORACLE 9i] invalid 상태인 procedure는 dba_procedures에서 조회불가

|
select status
      ,count(*) cnt
  from dba_objects
 where owner = upper('portal')
   and object_name like upper('sp_bip_user%')
   and object_type = upper('procedure')
 group by status

STATUS         CNT
------- ----------
INVALID          1
VALID            7

2 rows selected.

select count(*) cnt
  from dba_procedures
 where owner = upper('portal')
   and object_name like upper('sp_bip_user%')

       CNT
----------
         7

1 row selected.
왜 dba_procedures 에는 status가 없나 했음.
And

[Oracle] Add Partition 또는 Split Partition시 ORA-00959 에러 해결방법

|
SQL> !oerr ora 959
00959, 00000, "tablespace '%s' does not exist"
// *Cause:
// *Action:
확인 할 사항

select tablespace_name
  from dba_tables
 where owner = '[OWNER]'
   and table_name = '[TABLE NAME]'
;


결과에서 나온 테이블스페이스명이 정상적으로 존재하는지 또는 상태값이 정상인지 확인.

Partitioned Table의 경우


select def_tablespace_name
  from dba_part_tables
 where owner = '[OWNER]'
    and table_name = '[TABLE NAME]'
;

만약 존재하지 않는 테이블스페이스라면


alter table [OWNER].[TABLE NAME] modify default attributes tablespace [TABLESPACE NAME];



상위 명령을 실행하여 default tablespace를 정상적인 것으로 변경해줍니다.

그럼 만사 OK!!
And

[ORACLE] lock

|
select a.sid,
       decode(a.type,'MR', 'Media Recovery',
                     'RT', 'Redo Thread',
                     'UN', 'User Name',
                     'TX', 'Transaction',
                     'TM', 'DML',
                     'UL', 'PL/SQL User Lock',
                     'DX', 'Distributed Xaction',
                     'CF', 'Control File',
                     'IS', 'Instance State',
                     'FS', 'File Set',
                     'IR', 'Instance Recovery',
                     'ST', 'Disk Space Transaction',
                     'IR', 'Instance Recovery',
                     'TS', 'Temp Segment',
                     'IV', 'Library Cache Invalidation',
                     'LS', 'Log Start or Switch',
                     'RW', 'Row Wait',
                     'SQ', 'Sequence Number',
                     'TE', 'Extend Table',
                     'TT', 'Temp Table',
                     a.type) lock_type,
       decode(a.lmode,0, 'None', /* Non Lock equivalent */
                      1, 'Null', /* N */
                      2, 'Row-S (SS)', /* L */
                      3, 'Row-X (SX)', /* R */
                      3, 'Row-X (SX)', /* R */
                      4, 'Share', /* S */
                      5, 'S/Row-X (SSX)', /* C */
                      6, 'Exclusive', /* X */
                      to_char(a.lmode)) mode_held,
                      decode(a.request,
                      0, 'None', /* Mon Lock equivalent */
                      1, 'Null', /* N */
                      2, 'Row-S (SS)', /* L */
                      3, 'Row-X (SX)', /* R */
                      4, 'Share', /* S */
                      5, 'S/Row-X (SSX)', /* C */
                      6, 'Exclusive', /* X */
                      to_char(a.request)) mode_requested,
       to_char(a.id1) lock_id1, to_char(a.id2) lock_id2
  from v$lock a
 where (id1,id2) in (select b.id1, b.id2
                       from v$lock b
                      where b.id1=a.id1
                        and b.id2=a.id2
                        and b.request>0)
;
And

[ORACLE] 권한 조회 VIEW

|
데이타 사전 테이블 설명
ROLE_SYS_PRIVS role에 부여된 시스템 권한
ROLE_TAB_PRIVS role에 부여된 테이블 권한
USER_ROLE_PRIVS 사용자가 액세스할 수 있는 role
USER_TAB_PRIVS_MADE 사용자가 부여한 객권한
USER_TAB_PRIVS_RECD 사용자에게 부여된 객체 권한
USER_COL_PRIVS_RECD 특정 Column에 대하여 사용자에게
부여된 객체 권한

And

[ORACLE] dbms_metadata.get_ddl

|
select dbms_metadata.get_ddl('OBJECT_TYPE','OBJECT_NAME','OBJECT_OWNER') from dual;
And

[ORACLE] To dec - http://wiki.ex-em.com/index.php/To_dec 펌

|
십진수, 16진수, 8진수, 2진수 간의 변환을 수행하는 함수들로, Tom Kyte(http://asktom.oracle.com)에 의해 작성되었다.

/* the following hex conversion code is from Tom Kyte */
create or replace function to_base( p_dec in number, p_base in number ) 
return varchar2
is
l_str varchar2(255) default NULL;
l_num number default p_dec;
l_hex varchar2(16) default '0123456789ABCDEF';
begin
if ( trunc(p_dec) <> p_dec OR p_dec < 0 ) then
raise PROGRAM_ERROR;
end if;
loop
l_str := substr( l_hex, mod(l_num,p_base)+1, 1 ) || l_str;
l_num := trunc( l_num/p_base );
exit when ( l_num = 0 );
end loop;
return l_str;
end to_base;
/


create or replace function to_dec
( p_str in varchar2, 
  p_from_base in number default 16 ) return number
is
l_num   number default 0;
l_hex   varchar2(16) default '0123456789ABCDEF';
begin
for i in 1 .. length(p_str) loop
l_num := l_num * p_from_base + instr(l_hex,upper(substr(p_str,i,1)))-1;
end loop;
return l_num;
end to_dec;
/
show errors

create or replace function to_hex( p_dec in number ) return varchar2
is
begin
return to_base( p_dec, 16 );
end to_hex;
/
create or replace function to_bin( p_dec in number ) return varchar2
is
begin
return to_base( p_dec, 2 );
end to_bin;
/
create or replace function to_oct( p_dec in number ) return varchar2
is
begin
return to_base( p_dec, 8 );
end to_oct;
/
And
prev | 1 | 2 | 3 | 4 | next