2014. 12. 30. 13:50

바인드 변수값 테이블

오라클에서 바인드된 변수값을 확인하기위해서는 Trace를 하면되는데 여건이 안되면 아래 테이블 또는 뷰로 검색한다

제약사항 : 10G 이상
이하버전은 Trace를 사용하세요

SYS.V_$SQL_BIND_CAPTURE
DBA_HIST_SQLBIND

관련뷰
SYS.V_$SQL
SYS.V_$SQL_PLAN
SYS.V_$SQLAREA
SYS.V_$SQL_BIND_DATA
SYS.V_$SQL_BIND_METADATA

'-=-= 컴퓨터 =-=- > Database' 카테고리의 다른 글

[오라클] CREATE TABLE AS SELECT  (0) 2014.12.17
오라클 일별 통계  (0) 2014.10.29
[오라클] 월별 통계  (0) 2014.03.01
오라클 상태 조회  (0) 2014.03.01
[오라클 / PL-SQL] 오라클 예외처리 및 기본 예제  (0) 2014.02.17
2014. 12. 17. 15:56

[오라클] CREATE TABLE AS SELECT

CREATE TABLE 테이블명 (컬럼명1,컬럼명2) AS

SELECT 컬럼명1,컬럼명2

FROM 테이블명

WHERE 조건


조회한 후 인서트시 컬럼명을 변경할때 사용됨

'-=-= 컴퓨터 =-=- > Database' 카테고리의 다른 글

바인드 변수값 테이블  (0) 2014.12.30
오라클 일별 통계  (0) 2014.10.29
[오라클] 월별 통계  (0) 2014.03.01
오라클 상태 조회  (0) 2014.03.01
[오라클 / PL-SQL] 오라클 예외처리 및 기본 예제  (0) 2014.02.17
2014. 10. 29. 10:55

오라클 일별 통계

오라클 SH 스키마 필요

 

SELECT
    CUST_ID, YYYYMM, SUM("01") AS "1일", SUM("02") AS "2일", SUM("03") AS "3일", SUM("04") AS "4일", SUM("05") AS "5일", SUM("06") AS "6일",
    SUM("07") AS "7일", SUM("08") AS "8일", SUM("09") AS "9일", SUM("10") AS "10일", SUM("11") AS "11일", SUM("12") AS "12일",
    SUM("13") AS "13일", SUM("14") AS "14일", SUM("15") AS "15일", SUM("16") AS "16일", SUM("17") AS "17일", SUM("18") AS "18일",
    SUM("19") AS "19일", SUM("20") AS "20일", SUM("21") AS "21일", SUM("22") AS "22일", SUM("23") AS "23일", SUM("24") AS "24일",
    SUM("25") AS "25일", SUM("26") AS "26일", SUM("27") AS "27일", SUM("28") AS "28일", SUM("29") AS "29일", SUM("30") AS "30일", SUM("31") AS "31일",
    SUM(AMOUNT_SOLD) AS "총계"
FROM(
        SELECT CUST_ID, TO_CHAR(TIME_ID,'YYYY-MM') AS YYYYMM, TO_CHAR(TIME_ID,'DD') AS DD, AMOUNT_SOLD
        , DECODE(TO_CHAR(TIME_ID,'DD'), '01', AMOUNT_SOLD, 0) AS "01"
        , DECODE(TO_CHAR(TIME_ID,'DD'), '02', AMOUNT_SOLD, 0) AS "02"
        , DECODE(TO_CHAR(TIME_ID,'DD'), '03', AMOUNT_SOLD, 0) AS "03"
        , DECODE(TO_CHAR(TIME_ID,'DD'), '04', AMOUNT_SOLD, 0) AS "04"
        , DECODE(TO_CHAR(TIME_ID,'DD'), '05', AMOUNT_SOLD, 0) AS "05"
        , DECODE(TO_CHAR(TIME_ID,'DD'), '06', AMOUNT_SOLD, 0) AS "06"
        , DECODE(TO_CHAR(TIME_ID,'DD'), '07', AMOUNT_SOLD, 0) AS "07"
        , DECODE(TO_CHAR(TIME_ID,'DD'), '08', AMOUNT_SOLD, 0) AS "08"
        , DECODE(TO_CHAR(TIME_ID,'DD'), '09', AMOUNT_SOLD, 0) AS "09"
        , DECODE(TO_CHAR(TIME_ID,'DD'), '10', AMOUNT_SOLD, 0) AS "10"
        , DECODE(TO_CHAR(TIME_ID,'DD'), '11', AMOUNT_SOLD, 0) AS "11"
        , DECODE(TO_CHAR(TIME_ID,'DD'), '12', AMOUNT_SOLD, 0) AS "12"
        , DECODE(TO_CHAR(TIME_ID,'DD'), '13', AMOUNT_SOLD, 0) AS "13"
        , DECODE(TO_CHAR(TIME_ID,'DD'), '14', AMOUNT_SOLD, 0) AS "14"
        , DECODE(TO_CHAR(TIME_ID,'DD'), '15', AMOUNT_SOLD, 0) AS "15"
        , DECODE(TO_CHAR(TIME_ID,'DD'), '16', AMOUNT_SOLD, 0) AS "16"
        , DECODE(TO_CHAR(TIME_ID,'DD'), '17', AMOUNT_SOLD, 0) AS "17"
        , DECODE(TO_CHAR(TIME_ID,'DD'), '18', AMOUNT_SOLD, 0) AS "18"
        , DECODE(TO_CHAR(TIME_ID,'DD'), '19', AMOUNT_SOLD, 0) AS "19"
        , DECODE(TO_CHAR(TIME_ID,'DD'), '20', AMOUNT_SOLD, 0) AS "20"
        , DECODE(TO_CHAR(TIME_ID,'DD'), '21', AMOUNT_SOLD, 0) AS "21"
        , DECODE(TO_CHAR(TIME_ID,'DD'), '22', AMOUNT_SOLD, 0) AS "22"
        , DECODE(TO_CHAR(TIME_ID,'DD'), '23', AMOUNT_SOLD, 0) AS "23"
        , DECODE(TO_CHAR(TIME_ID,'DD'), '24', AMOUNT_SOLD, 0) AS "24"
        , DECODE(TO_CHAR(TIME_ID,'DD'), '25', AMOUNT_SOLD, 0) AS "25"
        , DECODE(TO_CHAR(TIME_ID,'DD'), '26', AMOUNT_SOLD, 0) AS "26"
        , DECODE(TO_CHAR(TIME_ID,'DD'), '27', AMOUNT_SOLD, 0) AS "27"
        , DECODE(TO_CHAR(TIME_ID,'DD'), '28', AMOUNT_SOLD, 0) AS "28"
        , DECODE(TO_CHAR(TIME_ID,'DD'), '29', AMOUNT_SOLD, 0) AS "29"
        , DECODE(TO_CHAR(TIME_ID,'DD'), '30', AMOUNT_SOLD, 0) AS "30"
        , DECODE(TO_CHAR(TIME_ID,'DD'), '31', AMOUNT_SOLD, 0) AS "31"
        FROM SH.SALES
        --WHERE TO_CHAR(TIME_ID,'YYYYMM') = '199801'
)GROUP BY CUST_ID, YYYYMM
ORDER BY CUST_ID ASC, YYYYMM ASC

 

 

결과

 

 

2014. 3. 1. 15:48

[오라클] 월별 통계

SH 스키마 필요 // 년도별 월별 통계 //2014.10.29 수정

 

SELECT
    CUST_ID, YYYY, SUM("01") AS "1월", SUM("02") AS "2월", SUM("03") AS "3월", SUM("04") AS "4월", SUM("05") AS "5월", SUM("06") AS "6월",
    SUM("07") AS "7월", SUM("08") AS "8월", SUM("09") AS "9월", SUM("10") AS "10월", SUM("11") AS "11월", SUM("12") AS "12월",
    SUM(AMOUNT_SOLD) AS "총계"
FROM(
        SELECT CUST_ID, TO_CHAR(TIME_ID,'YYYY') AS YYYY, TO_CHAR(TIME_ID,'MM') AS MM, TO_CHAR(TIME_ID,'DD') AS DD, AMOUNT_SOLD
        , DECODE(TO_CHAR(TIME_ID,'MM'), '01', AMOUNT_SOLD, 0) AS "01"
        , DECODE(TO_CHAR(TIME_ID,'MM'), '02', AMOUNT_SOLD, 0) AS "02"
        , DECODE(TO_CHAR(TIME_ID,'MM'), '03', AMOUNT_SOLD, 0) AS "03"
        , DECODE(TO_CHAR(TIME_ID,'MM'), '04', AMOUNT_SOLD, 0) AS "04"
        , DECODE(TO_CHAR(TIME_ID,'MM'), '05', AMOUNT_SOLD, 0) AS "05"
        , DECODE(TO_CHAR(TIME_ID,'MM'), '06', AMOUNT_SOLD, 0) AS "06"
        , DECODE(TO_CHAR(TIME_ID,'MM'), '07', AMOUNT_SOLD, 0) AS "07"
        , DECODE(TO_CHAR(TIME_ID,'MM'), '08', AMOUNT_SOLD, 0) AS "08"
        , DECODE(TO_CHAR(TIME_ID,'MM'), '09', AMOUNT_SOLD, 0) AS "09"
        , DECODE(TO_CHAR(TIME_ID,'MM'), '10', AMOUNT_SOLD, 0) AS "10"
        , DECODE(TO_CHAR(TIME_ID,'MM'), '11', AMOUNT_SOLD, 0) AS "11"
        , DECODE(TO_CHAR(TIME_ID,'MM'), '12', AMOUNT_SOLD, 0) AS "12"
        FROM SH.SALES
--        WHERE TO_CHAR(TIME_ID,'YYYY') BETWEEN 1999 AND 2000 --특정년도 범위

--        AND TO_CHAR(TIME_ID,'YYYYMM') = '199801'  --특정년월
--        AND TO_CHAR(TIME_ID,'MM') = 05 --특정달만
)GROUP BY CUST_ID, YYYY
ORDER BY CUST_ID ASC, YYYY ASC

 

결과

 

 

 

2014. 3. 1. 13:48

오라클 상태 조회

1. 세션별 CPU Time, Memory 사용량
 
select s.sid, s.serial#, p.spid as "os pid", s.username, s.module, s.sql_id, event, seconds_in_wait,
st.value/100 as "cpu sec",
round(pga_used_mem/1024/1024) "pga_tot(mb)",
round(pga_used_mem/1024/1024) "pga_per_sess(mb)"
from v$sesstat st, v$statname sn, v$session s, v$process p
where sn.name = 'CPU used by this session' -- cpu
and st.statistic# = sn.statistic#
and st.sid = s.sid
and s.paddr = p.addr
and s.last_call_et < 1800 -- active within last 1/2 hour
and s.logon_time > (SYSDATE - 240/1440) -- sessions logged on within 4 hours
order by st.value

 
 
 
 
2. Client별 Memory 사용량
 
select machine,status,count(*) cnt, 
       round(sum(pga_used_mem)/1024/1024) "pga_tot(mb)",
       round(sum(pga_used_mem)/count(*)/1024/1024) "pga_per_sess(mb)"
from v$session s, v$process p
where 1=1
--and s.status='active'
and s.paddr=p.addr
and type <> 'BACKGROUND'
group by machine,status
order by 1

2014. 2. 17. 09:35

[오라클 / PL-SQL] 오라클 예외처리 및 기본 예제

CREATE OR REPLACE PROCEDURE SP_USER_CONTROL(   
    SEL_MODE IN VARCHAR2,
    P_X_ID IN X_TEMP_TABLE.X_ID%TYPE,
    P_X_PW IN X_TEMP_TABLE.X_PW%TYPE,
    ERROR_CODE OUT VARCHAR2, --에러코드 리턴
    ERROR_MSG OUT VARCHAR2 --에러메시지
)IS
    V_ERROR_CODE VARCHAR2(30); --예외코드 변수
    V_ERROR_MSG VARCHAR2(1000); --예외메시지 변수
    V_CNT NUMBER;
    CALLEXT EXCEPTION; --사용자 예외 선언
BEGIN   
    IF SEL_MODE='1' THEN --INSERT
        DBMS_OUTPUT.PUT_LINE('INSERT');
        BEGIN
            INSERT INTO X_TEMP_TABLE VALUES(P_X_ID,P_X_PW);
            EXCEPTION WHEN DUP_VAL_ON_INDEX THEN
                            V_ERROR_CODE:='E001';
                            V_ERROR_MSG:='중복된 데이터로 인해 입력에 실패하엿습니다.';
                            RAISE CALLEXT; --사용자 예외 던지기
                      WHEN OTHERS THEN
                            RAISE; --예외 던지기
        END;
    ELSIF SEL_MODE='2' THEN --UPDATE
        DBMS_OUTPUT.PUT_LINE('UPDATE');
        BEGIN           
            SELECT COUNT(*) INTO V_CNT FROM X_TEMP_TABLE WHERE X_ID = P_X_ID;
            IF V_CNT > 0 THEN
                UPDATE X_TEMP_TABLE SET X_ID = P_X_ID, X_PW = P_X_PW WHERE X_ID = P_X_ID;
            ELSE
               V_ERROR_CODE:='E002';
               V_ERROR_MSG:='대상 데이터가 검색되지 않앗습니다.';
               RAISE CALLEXT; --사용자 예외 던지기
            END IF;
           
            EXCEPTION WHEN OTHERS THEN
                      RAISE; --예외 던지기
        END;       
    ELSIF SEL_MODE='3' THEN --DELETE
        DBMS_OUTPUT.PUT_LINE('DELETE');
        BEGIN           
            SELECT COUNT(*) INTO V_CNT FROM X_TEMP_TABLE WHERE X_ID = P_X_ID;
            IF V_CNT > 0 THEN
                DELETE FROM X_TEMP_TABLE WHERE X_ID = P_X_ID;
            ELSE
               V_ERROR_CODE:='E002';
               V_ERROR_MSG:='대상 데이터가 검색되지 않앗습니다.';
               RAISE CALLEXT; --사용자 예외 던지기
            END IF;
           
            EXCEPTION WHEN OTHERS THEN
                      RAISE; --예외 던지기
        END;
    ELSIF SEL_MODE='4' THEN --TRUNCATE
        DBMS_OUTPUT.PUT_LINE('TRUNCATE');
        BEGIN           
            EXECUTE IMMEDIATE 'TRUNCATE TABLE X_TEMP_TABLE';
            EXCEPTION WHEN OTHERS THEN
                      RAISE; --예외 던지기
        END;
    ELSE
        RAISE CALLEXT;
    END IF;
   
    ERROR_CODE:='E000';
    ERROR_MSG:='정상적으로 처리되엇습니다.';
    COMMIT;
   
    EXCEPTION
        WHEN CALLEXT THEN --사용자 예외
             ERROR_CODE:=V_ERROR_CODE;
             ERROR_MSG:=V_ERROR_MSG;
             ROLLBACK;
        WHEN NO_DATA_FOUND THEN
             ERROR_CODE:='E002';
             ERROR_MSG:='데이터를 찾을수가 없습니다.';
             ROLLBACK;
        WHEN OTHERS THEN
             ERROR_CODE:='E004';
             ERROR_MSG:=SQLERRM || SQLCODE;   
             ROLLBACK;
END SP_USER_CONTROL;

2013. 3. 11. 09:37

java.sql.SQLException: 논리적 핸들이 더 이상 유효하지 않습니다

java.sql.SQLException: 논리적 핸들이 더 이상 유효하지 않습니다

 

위와 같은 오류 발생시 제일먼저 확인해야할것은 JDBC CONNECTION 관리가 제대로 되고있는지부터 확인해야한다.

 

참조  : http://www.okjsp.pe.kr/seq/50687

 

 

2013. 2. 20. 10:23

오라클 split 함수

 
CREATE OR REPLACE FUNCTION FN_GET_SPLIT(
    IN_STR         IN  VARCHAR2,    
    IN_LEVEL       IN  INT,         
    IN_DELIMETER   IN  VARCHAR2,
    IN_DEFAULT_VAL IN  VARCHAR2     
)
RETURN VARCHAR2

IS
    V_RETURN              VARCHAR2(200);    
    STRVALUE              VARCHAR2(4000) := IN_STR; 
    DEFAULT_RETURN_VAL    VARCHAR2(4000) := IN_DEFAULT_VAL;
    IDX INT;    
    ILEVEL INT := 0;

BEGIN

    V_RETURN := '';

    -- 문자열이 없으면 기본 리턴값 반환 후 종료
    IF NVL(STRVALUE,'NO_STRING') = 'NO_STRING' THEN
        RETURN DEFAULT_RETURN_VAL;
    END IF;
        
    LOOP
        --구분자 인덱스 확인
        IDX := INSTR(STRVALUE, IN_DELIMETER);
        
        IF IDX > 0 THEN --구분자로 문자를 찾은경우
                                    
            ILEVEL := ILEVEL + 1;
            
            -- 현재 레벨이 원하는 레벨이면 현재 문자열 반환 AND 레벨이 -1인경우는 마지막까지 LOOP
            IF ILEVEL = IN_LEVEL AND IN_LEVEL != -1 THEN
                V_RETURN := SUBSTR(STRVALUE, 1, IDX-1);
                EXIT;
            END IF;
                        
            STRVALUE := SUBSTR(STRVALUE, IDX + LENGTH(IN_DELIMETER));
        ELSE  -- 구분자가 없을 경우, 문자열을 그대로 반환
        
            IF ILEVEL = 0 THEN
                --구분자가 포함이 안되었지만 레벨이 1인경우 문자 그대로 반환
                IF IN_LEVEL = 1 THEN
                    V_RETURN := STRVALUE;
                ELSE
                    V_RETURN := '';
                END IF;
            ELSE
                -- 마지막 문자열일 경우
                ILEVEL := ILEVEL + 1;
                
                -- 마지막을 원하는 경우 마지막 문자열 반환 / -1은 레벨을 모를경우 구분자의 마지막 문자열 반환
                IF ILEVEL = IN_LEVEL OR IN_LEVEL = -1 THEN
                        V_RETURN := STRVALUE;
                ELSE
                    -- 원하는 레벨의 값이 없을 경우, 공백 반환
                    V_RETURN := '';        
                END IF;
            END IF;
            
            EXIT; --반복 탈출문
            
        END IF;
    END LOOP;    
    
    --최종결과 리턴
    RETURN NVL(V_RETURN, DEFAULT_RETURN_VAL);
        
    EXCEPTION
         WHEN OTHERS THEN
              RETURN SQLERRM;
END FN_GET_SPLIT;
2012. 10. 31. 13:38

오라클 connect by 예제

connecty by 사용 전

WITH A AS(
    SELECT 'A' AS CODE, '' AS P_CODE , '인사팀' AS TEAM_NAME FROM DUAL
    UNION ALL
    SELECT 'B' AS CODE, '' AS P_CODE , '재무팀' AS TEAM_NAME  FROM DUAL
    UNION ALL
    SELECT 'C' AS CODE, '' AS P_CODE , '삽질팀' AS TEAM_NAME  FROM DUAL
    UNION ALL
    SELECT 'D' AS CODE, 'A' AS P_CODE , '김우진' AS TEAM_NAME  FROM DUAL
    UNION ALL
    SELECT 'E' AS CODE, 'B' AS P_CODE , '이동수' AS TEAM_NAME  FROM DUAL
    UNION ALL
    SELECT 'F' AS CODE, 'C' AS P_CODE , '이진수' AS TEAM_NAME  FROM DUAL
    UNION ALL
    SELECT 'G' AS CODE, 'C' AS P_CODE , '조둔서' AS TEAM_NAME  FROM DUAL
    UNION ALL
    SELECT 'H' AS CODE, 'B' AS P_CODE , '개뿔딱' AS TEAM_NAME  FROM DUAL
)
SELECT A.*
FROM   A;

 

connecty by 사용 후
WITH A AS(
    SELECT 'A' AS CODE, '' AS P_CODE , '인사팀' AS TEAM_NAME FROM DUAL
    UNION ALL
    SELECT 'B' AS CODE, '' AS P_CODE , '재무팀' AS TEAM_NAME  FROM DUAL
    UNION ALL
    SELECT 'C' AS CODE, '' AS P_CODE , '삽질팀' AS TEAM_NAME  FROM DUAL
    UNION ALL
    SELECT 'D' AS CODE, 'A' AS P_CODE , '김우진' AS TEAM_NAME  FROM DUAL
    UNION ALL
    SELECT 'E' AS CODE, 'B' AS P_CODE , '이동수' AS TEAM_NAME  FROM DUAL
    UNION ALL
    SELECT 'F' AS CODE, 'C' AS P_CODE , '이진수' AS TEAM_NAME  FROM DUAL
    UNION ALL
    SELECT 'G' AS CODE, 'C' AS P_CODE , '조둔서' AS TEAM_NAME  FROM DUAL
    UNION ALL
    SELECT 'H' AS CODE, 'B' AS P_CODE , '개뿔딱' AS TEAM_NAME  FROM DUAL
)
SELECT CODE,P_CODE,LPAD(' ',  8 * (LEVEL-1))||TEAM_NAME
FROM   A
START WITH P_CODE IS NULL
CONNECT BY  PRIOR CODE = P_CODE;

2012. 5. 25. 11:46

오라클 리스너 로그 설정 해제

 

 

참조주소 :

http://ssiso.net/cafe/club/club1/board1/content.php?board_code=oracle%7Coratip&idx=1193&club=oracle&cp=7&cb=1&search=&search_word=

 

 

 

$ lsnrctl status
Listener Parameter File   /oracle/product/RAC/network/admin/listener.ora
Listener Log File         /oracle/product/RAC/network/log/listener_db2.log
Listening Endpoints Summary...
$ lsnrctl set log_status off
LISTENER parameter "log_status" set to OFF
The command completed successfully
$ lsnrctl status
Listener Parameter File   /oracle/product/RAC/network/admin/listener.ora
Listening Endpoints Summary...
$ lsnrctl reload
The command completed successfully
$ lsnrctl status
Listener Parameter File   /oracle/product/RAC/network/admin/listener.ora
Listener Log File         /oracle/product/RAC/network/log/listener_db2.log
Listening Endpoints Summary...

$ lsnrctl set log_status on
LISTENER parameter "log_status" set to ON

/oracle/product/RAC/network/admin/listener.ora
------------------------------------------------
LOGGING_LISTENER = OFF

2012. 5. 9. 15:38

[오류] PLS-00215: String length constraints must be in range (1 .. 32767)

에러유형

VARCHAR2

VARCHAR2(-1)

 

VARCHAR2(50)

 

조치 : varchar2의 크기를 1..32767 범위안에 잇어야함.

2012. 5. 9. 11:08

오라클 인덱스 생성 및 테이블스페이스변경

인덱스 생성

CREATE [ UNIQUE ] INDEX MAPPING_INFO_IDX_01 ON MAPPING_INFO(REG_NO ASC, DOC_TYPE ASC ,ORGN_ID ASC);

 

인덱스 테이블 스페이스 변경

ALTER INDEX MAPPING_INFO_IDX_01 REBUILD TABLESPACE DATA;

 

인덱스 정보 확인

SELECT * FROM USER_INDEXES WHERE INDEX_NAME = 'MAPPING_INFO_IDX_01 ';

 

인덱스 제거

DROP INDEX MAPPING_INFO_IDX_01;

 

2012. 4. 9. 13:38

오라클 DBMS_output 사용

원본 : http://radiocom.kunsan.ac.kr/lecture/oracle/variable/serveroutput.html


프로시저 결과를 화면에 출력하고 싶을때 사용


SQL> show serveroutput serveroutput OFF SQL> set serveroutput on


----테스트 SQL> begin 2 dbms_output.put_line('확인'); 3 end; 4 / 확인 > 출력되면 성공 PL/SQL procedure successfully completed.

2012. 4. 6. 10:31

오라클 달력 생성 쿼리


SELECT

--달력 맵핑

        MIN(DECODE(TO_CHAR(DATES,'D'),1,TO_CHAR(DATES,'DD'))) 일

        ,MIN(DECODE(TO_CHAR(DATES,'D'),2,TO_CHAR(DATES,'DD'))) 월

        ,MIN(DECODE(TO_CHAR(DATES,'D'),3,TO_CHAR(DATES,'DD'))) 화

        ,MIN(DECODE(TO_CHAR(DATES,'D'),4,TO_CHAR(DATES,'DD'))) 수

        ,MIN(DECODE(TO_CHAR(DATES,'D'),5,TO_CHAR(DATES,'DD'))) 목

        ,MIN(DECODE(TO_CHAR(DATES,'D'),6,TO_CHAR(DATES,'DD'))) 금

        ,MIN(DECODE(TO_CHAR(DATES,'D'),7,TO_CHAR(DATES,'DD'))) 토

FROM(

    SELECT (MAKE_DATES + LEVEL - 1) DATES   --달력 하위 일수 구하기

    FROM(

        SELECT (TO_DATE('200701','YYYYMM')) MAKE_DATES FROM DUAL --기준달력 생성

    )

    CONNECT BY (MAKE_DATES+LEVEL-1) <= LAST_DAY(MAKE_DATES) --마지막일자

)

GROUP BY DECODE(TO_CHAR(DATES,'D'),1, TO_CHAR(DATES,'W')+1,TO_CHAR(DATES,'W')) --합치기

ORDER BY DECODE(TO_CHAR(DATES,'D'),1, TO_CHAR(DATES,'W')+1,TO_CHAR(DATES,'W')); --주차 정렬

2012. 4. 4. 20:31

오라클 콘솔에서 화면 초기화 명령어



cl scr 화면초기화

2012. 3. 28. 09:59

오라클 plan table 생성 및 권한부여

 

 

원 저작자 : http://www.bysql.net/index.php?document_srl=10922&mid=ORACLE

[oracle@localhost ~]$ sqlplus '/as sysdba'

plan table 생성
SQL> conn scott/tiger
Connected.
SQL> @$ORACLE_HOME/rdbms/admin/utlxplan.sql

Table created.
플랜 테이블명 : PLAN_TABLE

오렌지 플랜테이블 설정

PLAN TOOL(ALT+F7) -> OPTION -> OPTIONS -> PLAN TABLE -> PLAN_TABLE(플랜테이블명)

PLUSTRACE 룰 생성

SQL> conn sys/manager as sysdba
Connected.

SQL>
SQL> @$ORACLE_HOME/sqlplus/admin/plustrce.sql
SQL>

plustrce.sql 내용 시작

//기존 롤 제거
SQL> drop role plustrace;
drop role plustrace
          *
ERROR at line 1:
ORA-01919: role 'PLUSTRACE' does not exist

//롤 생성
SQL> create role plustrace;

Role created.
//권한부여
SQL>
SQL> grant select on v_$sesstat to plustrace;

Grant succeeded.

SQL> grant select on v_$statname to plustrace;

Grant succeeded.

SQL> grant select on v_$mystat to plustrace;

Grant succeeded.

SQL> grant plustrace to dba with admin option;

Grant succeeded.

plustrce.sql 내용 끝

 

SQL>
SQL> set echo off
SQL> grant plustrace to scott(사용자);

Grant succeeded.


 

PLAN 보기 확인

 EXPLAIN PLAN FOR
  2  쿼리~~~

====================

SQL> conn scott/tiger
Connected.
SQL> set linesize 120
SQL> set autot on   or  set autot trace exp
SQL> select * from emp where rownum=1;

     EMPNO ENAME      JOB              MGR HIREDATE         SAL       COMM     DEPTNO
---------- ---------- --------- ---------- --------- ---------- ---------- ----------
      7369 SMITH      CLERK           7902 17-DEC-80        800                    20


Execution Plan
----------------------------------------------------------
Plan hash value: 1973284518

---------------------------------------------------------------------------
| Id  | Operation          | Name | Rows  | Bytes | Cost (%CPU)| Time     |
---------------------------------------------------------------------------
|   0 | SELECT STATEMENT   |      |     1 |    87 |     2   (0)| 00:00:01 |
|*  1 |  COUNT STOPKEY     |      |       |       |            |          |
|   2 |   TABLE ACCESS FULL| EMP  |    14 |  1218 |     2   (0)| 00:00:01 |
---------------------------------------------------------------------------

수동 plan 설정

DESC PLAN_TABLE; <플랜테이블 확인

EXPLAIN PLAN SET STATEMENT_ID = 'TEMP1'
INTO PLAN_TABLE FOR
SELECT *
FROM MEMBER
WHERE 1=1;

플랜확인
SELECT ID, PARENT_ID P_ID
,LPAD(' ',2*(LEVEL))||OPERATION,OPTIONS, OBJECT_NAME
FROM PLAN_TABLE
START WITH ID =0 AND STATEMENT_ID = 'TEMP1'
CONNECT BY PRIOR ID = PARENT_ID AND STATEMENT_ID = 'TEMP1';

 

2012. 3. 26. 17:54

DB 프로시저, 트리거 소스 확인

SELECT * FROM USER_SOURCE
WHERE TYPE = 'PROCEDURE'
AND TEXT LIKE '%REGIST_DATE%'
ORDER BY NAME ASC;
2012. 2. 20. 10:55

오라클 락 조회 및 접속자 쿼리 확인

SELECT
       SUBSTR(SO.OBJECT_NAME,1,12) "오브젝트명"
      , SO.OBJECT_TYPE
   /*   ,DECODE(SO.OBJECT_TYPE
                      , 1, 'INDEX'
                      , 2, 'TABLE'
                      , 3, 'CLUST'
                      , 4, 'VIEW '   6
                      , 5, 'SYNON'
                      , 6, 'SEQUE'
                      , 7, 'PROCE'
                      , 8, 'FUNCT'
                      , 9, 'PACKA'
                      ,11, 'PAC-B'
                      ,12, 'TRIGG'
                      ,TO_CHAR(SO.OBJECT_TYPE,'9999')
             )                 "TYPE"    */
      ,SUBSTR(VS.OSUSER,1,6)     "로그인"
      ,VP.TERMINAL               "터미날"
      ,SUBSTR(VP.SPID,1,5)       "UXPID"
      ,SUBSTR(VS.PROCESS,1,6)    "UXPPID"
      ,SUBSTR(VS.USERNAME,1,4)   "USER"
      ,SUBSTR(DECODE(VS.COMMAND,'2','INSERT'
                               ,'3','SELECT'
                               ,'6','UPDATE'
                               ,'7','DELETE'
                               ,VS.COMMAND
             ),1,6)
                                 "명령어"
      ,DECODE(VL.LMODE,1,'NULL',
                       2,'ROW-SHARE',
                       3,'ROW-EXCLUSIVE',
                       4,'SHARE',
                       5,'SHARE-ROW-EXCLU',
                       6,'EXCLU') "LOCK-상태"
      ,'ALTER SYSTEM KILL SESSION '||CHR(39)||VS.SID||','|| VS.SERIAL# ||CHR(39)||';'
  FROM
       V$LOCK    VL
     , V$SESSION VS
     , V$PROCESS VP
     , OBJ       SO
 WHERE VS.PADDR     = VP.ADDR
   AND VL.SID       = VS.SID
 --  AND VS.USERNAME != 'ORACLE8'
   AND VL.TYPE      = 'TM'
   AND SO.OBJECT_ID      = VL.ID1
 ORDER BY 1,2 ;

 

/* 락걸린 테이블 확인 */
SELECT do.object_name, do.owner, do.object_type, do.owner,
vo.xidusn, vo.session_id, vo.locked_mode
FROM
v$locked_object vo , dba_objects do
WHERE vo.object_id = do.object_id ;

/*  해당테이블이 락에 걸렸는지.. */
SELECT A.SID, A.SERIAL#, B.TYPE, C.OBJECT_NAME
FROM V$SESSION A, V$LOCK B, DBA_OBJECTS C
WHERE A.SID=B.SID AND B.ID1=C.OBJECT_ID
AND B.TYPE='TM' AND C.OBJECT_NAME IN ('테이블명');

/* 락발생 사용자와 sql, object 조회 */

SELECT distinct x.session_id, a.serial#,
d.object_name, a.machine, a.terminal,
a.program, b.address, b.piece, b.sql_text
FROM v$locked_object x, v$session a, v$sqltext b, dba_objects d
WHERE x.session_id = a.sid and
x.object_id = d.object_id and
a.sql_address = b.address
order by b.address,b.piece;

/* 락 발생 사용자확인 */

SELECT distinct x.session_id, a.serial#,
d.object_name, a.machine, a.terminal, a.program,
a.logon_time , 'alter system kill session ''' || a.sid ||',' || a.serial# || ''';' as KILL_CMD
FROM gv$locked_object x, gv$session a, dba_objects d
WHERE x.session_id = a.sid and x.object_id = d.object_id
order by logon_time;

/* 접속 사용자 제거 */

–alter system kill session ’session_id,serial#’;
alter system kill session '26,6044';  -- '26(세션id),6044(시리얼번호)';

/* 현재 접속자의 sql 분석 */

SELECT distinct a.sid, a.serial#,
a.machine, a.terminal, a.program,
b.address, b.piece, b.sql_text
FROM v$session a, v$sqltext b
WHERE a.sql_address = b.address
order by a.sid, a.serial#,b.address,b.piece;

--오라클 환경설정 값 확인(세션, 프로세스)
select * from v$resource_limit;



참조 주소 : http://www.explab.net/?p=384

2012. 2. 17. 10:16

오라클 자동실행 스크립트

오라클 홈경로 : /u01/app/oracle/product/10.2.0/db_1/

vi /etc/rc.d/rc.local  수정
-- 시작시 자동실행

### Oracle Start ###
su - oracle -c /u01/app/oracle/product/10.2.0/db_1/bin/dbstart
su  - oracle -c /u01/app/oracle/product/10.2.0/db_1/bin/'lsnrctl start'
사용하면 추가
//  su  - oracle -c /u01/app/oracle/product/10.2.0/db_1/bin/'emctl start dbconsole'


실행 테스트
/u01/app/oracle/product/10.2.0/db_1/bin/dbstart
/u01/app/oracle/product/10.2.0/db_1/bin/'lsnrctl start'

실행시 오류
가 떨어지면
Failed to auto-start Oracle Net Listene using /ade/vikrkuma_new/oracle/bin/tnslsnr
Processing Database instance "orcl": log file /home/oracle/product/10g/startup.log
Processing Database instance "orcl": log file /home/oracle/product/10g/startup.log

>> dbstart 파일 수정
vi /u01/app/oracle/product/10.2.0/db_1/bin/dbstart

아래 부분 찾아 오라클 HOME 수정!

# Set this to bring up Oracle Net Listener
ORACLE_HOME_LISTNER=/u01/app/oracle/product/10.2.0/db_1
--오라클 홈경로의 데이터베이스 경로까지 설정 자동으로 /bin/tnslsnr 경로 추가됨 

/etc/oratab    수정
orcl:/u01/app/oracle/product/10.2.0/db_1:Y

2012. 2. 16. 09:50

오라클 오류코드표

2012. 1. 17. 15:15

데이터베이스 모델링 표기법

표기법 종류 및 이해
(Baker , IE 표기법 및 DB 강좌)
http://www.dbguide.net/db.db?cmd=view&boardUid=12845&boardConfigUid=9&categoryUid=216&boardIdx=31&boardStep=1

//기본표기법
http://info.raccoon.pe.kr/104


//스크립트로 ERD 그려주기
http://www.mungchung.com/xe/4099
2012. 1. 4. 11:14

[SQL콘솔-- COLUMN ] SELECT 시 컬럼 크기로 인해 화면 깨짐


SQL>   SET LINESIZE  200  <<<-- 가로 크기 (COL)
SQL>   SET PAGESIZE 100  <<<----세로 크기(ROW)

COL or COLUMN  컬럼명 FORMAT A10  <<<-- 컬럼크기를 100으로 하라(SIZE 관계 무/ 화면상크기)
COL or COLUMN  컬럼명 9999  <<<-- 컬럼의 숫자를 천단위로 표시하라

참고 사이트 : http://www.adp-gmbh.ch/ora/sqlplus/column.html
2011. 10. 17. 17:37

오라클 휴지통 테이블 지우기(10g)


휴지통 보기 명령어
 - SHOW RECYCLEBIN

휴지통 테이블 선택 삭제
- PURGE TABLE TABLE_NAME;

휴지통 비우기
- PURGE RECYCLEBIN

테이블 삭제 휴지통 거치지 않고 바로 삭제

CASCADE CONSTRAINTS PURGE 추가
2011. 10. 1. 17:52

Win7 Oracle 10g 설치전 설정


다운로드


환경설정 파일수정
[  ..\db\Disk1\install\oraparam.ini   ]
[Certified Versions]
#You can customise error message shown for failure, provide value for CERTIFIED_VERSION_FAILURE_MESSAGE
#Windows=5.0,5.1,5.2,6.0,6.1        <-- 추가

 
[  ..\db\Disk1\stage\prereq\db\refhost.xml     ] 
<OPERATING_SYSTEM>
      <VERSION VALUE="6.0"/>
    </OPERATING_SYSTEM>
 <!--Microsoft Windows 7-->         <--- 추가
 <OPERATING_SYSTEM>
  <VERSION VALUE="6.1"/>
 </OPERATING_SYSTEM>  
[ ..db\Disk1\stage\prereq\db_prereqs\db\refhost.xml  ]
 <!--Microsoft Windows 7-->
    <OPERATING_SYSTEM>
      <VERSION VALUE="6.1"/>
    </OPERATING_SYSTEM>
2011. 8. 20. 11:42

SQL상태에서 임시로 쉘로 빠져나가기


쿼리를 날리다가 임시로 명령어 모드로 나가고 싶다.

ex)

SQL> host                   ---> 쉘모드로 변경
[oracle@oracledb ~]$ exit   --> 쉘모드 종료 ->SQL로 변경
exit

SQL>

2011. 7. 9. 11:36

오라클 10g 한글깨짐 (UTF-8 변경)


환경

Cent OS 5.5 / Oracle 10g
------------------------------------------------------------------------------

SELECT * FROM sys.props$ where name='NLS_CHARACTERSET';  //캐릭터셋 확인


1. 프로파일 수정
export NLS_LANG=KOREAN_KOREA.UTF-8

export NLS_LANG=KOREAN_KOREA.KO16MSWIN949


2. 캐릭터셋 변경

C:\>sqlplus /nolog;

sql>conn /as sysdba;

 

변경하고자하는 캐릭터셋을 수정

== UTF-8 ==
sql>update sys.props$ set value$='UTF8' where name='NLS_CHARACTERSET';

sql>update sys.props$ set value$='UTF8' where name='NLS_NCHAR_CHARACTERSET';

sql>update sys.props$ set value$='KOREAN_KOREA.UTF8' where name='NLS_LANGUAGE';

= KO16MSWIN949 = //한글확장
sql>update sys.props$ set value$='KO16MSWIN949' where name='NLS_CHARACTERSET';

sql>update sys.props$ set value$='KO16MSWIN949' where name='NLS_NCHAR_CHARACTERSET';

sql>update sys.props$ set value$='KOREAN_KOREA.KO16MSWIN949' where name='NLS_LANGUAGE';

sql>commit;

 

재시작

sql>shutdown immediate;

sql>startup mount;

sql>alter system enable restricted session;

sql>alter system set job_queue_processes=0;

sql>alter system set aq_tm_processes=0;

sql>alter database open;

sql>alter database character set UTF8;

or  alter database character set KO16MSWIN949;

sql>shutdown immediate;

sql>startup;





참고 주소 : http://blog.stylegold.info/45
2011. 5. 4. 15:08

오라클 DB Name, SID, Global Name 쿼리


오라클 접속 후

1. DB_NAME
select name from v$database;


2. SID
select instance from v$thread;


3. Global Database Name

// select value$ from sys.props$ where name = "GLOBAL_DB_NAME";

or

select * from global_name;


리스너 수정시 활용
2011. 4. 13. 14:03

[oracle 11g] Enterprise Manager DB Control 시작 오류


오류내역

/oracle/11g/ccr/bin/emCCR -cron -silent start
The Oracle Configuration Manager state/writeable directory structure is incomplete.
OCM is not configured for this host or ORACLE_CONFIG_HOME. Please configure OCM first.
[oracle@oracledb ~]$ emctl status dbconsole
OC4J Configuration issue. /oracle/11g/oc4j/j2ee/OC4J_DBConsole_oracledb_orcl not found.
You have new mail in /var/spool/mail/oracle



EM 환경설정 재생성 명령어

emca -config dbcontrol db -repos recreate

emctl start dbconsole  시작 명령어

emctl status agent   agent 상태 확인
2011. 4. 13. 13:20

[TOAD] Could Not Locate OCI.DLL


Toad 이용시 접속 계정 생성시 Could Not Locate OCI.DLL 문구가 나오면

오라클 클라이언트를 설치해야하지만

오라클에서 설치 안하고 이용할수 있게 파일을 제공한다.

오라클 싸이트에 가면

Instant Client를 버전에 맞게 다운받아서 압축을 푼다.

http://www.oracle.com/technetwork/indexes/downloads/index.html

압축 푼 폴더를 PATH에다가 추가 시킨다.

PATH 설정은 시스템 속성에 있다.


ex)
C:\instantclient_11_2


ps. toad 이용시 위와 같은 방법을 하면된다.

직접 sql 쿼리를 날려 조회하고 싶다면 추가로 instant sqlplus 같은걸 깔아주고 셋팅을 해줘야한다.

2011. 4. 11. 14:14

오라클 EM

설치 완료 후 웹에서 오라클 상태 확인가능

http://www.allsoft.co.kr/bbs/board.php?bo_table=study4_2&wr_id=26