###################################################################################################

#   source site : blog.naver.com/tangamjaelt

#   master : 강용운

#   email : tangamjaelt@korea.com

#   last release : 2007.08.29

###################################################################################################

 

 

FOR UPDATE 절

- 커서 질의에 FOR UPDATE 절을 추가해서 영향을 받는 행을 잠글 수 있다.

- FOR UPDATE 절은 SELECT 문 맨 마지막에 온다. (ORDER BY 보다 뒤)

- SELECT ... FOR UPDATE문은 갱신 또는 삭제될 행을 식별한 다음 결과 집합에 있는 각 행을 잠근다.

- 행의 기존 값을 기반으로 갱신을 수행하려는 경우, 갱신 전에 다른 사용자가 해당 행을 변경하는 것을 방지하는 효과가 있다.

- SELECT 문 맨 마지막에 온다. ORDER BY 보다 뒤에...

- FOR UPDATE OF column_name 을 사용하여 해당 column_name이 있는 테이블에서만 행을 잠근다.

- NOWAIT 절은 다른 세션에서 해당 행을 잠근 경우, 무한정 대기하지 않고 즉시 오라클 오류를 반환하기 때문에 제어가 곧바로 프로그램으로 되돌아가 다른 작업을 수행할 수 있다.

- NOWAIT 를 생략하면 행을 사용할 수 있을 때까지 무한정 대기한다.

 

 

cursor_test4.sql

 DECLARE
        v_product mobile_phone.product_name%TYPE;
        v_brand mobile_phone.brand%TYPE;

 

     CURSOR cursor_mp(p_brand VARCHAR2) IS
         SELECT brand, product_name FROM mobile_phone
                WHERE brand = p_brand

         FOR UPDATE OF brand;    (NOWAIT를 사용하지 않았으므로 접근시 무한정 대기)


 BEGIN
        OPEN cursor_mp('LG');
        LOOP
                FETCH cursor_mp INTO v_brand, v_product;
                EXIT WHEN cursor_mp %NOTFOUND;
                DBMS_OUTPUT.PUT_LINE(v_brand || ' => ' ||  v_product);
        END LOOP;
        DBMS_OUTPUT.PUT_LINE(v_brand || ' 총 ' || cursor_mp%ROWCOUNT || ' 건');
        CLOSE cursor_mp;

 END;
 /

 

- NOWAIT를 사용하지 않은 경우이다.

- 2개 세션을 열어놓고 테스트 해보자.

 

 

- session 1 에서 Update를 하고 아직 commit 되지 않은 상태에서, session 2 가 커서에 FOR UPDATE 문으로 이미 잠겨있는 행을 잠그려고 하기 때문에 이미 해당 row가 사용중이라는 메시지와 함게 NOWAIT 절이 요구된다는 메시지를 뿌려주고 있다.

 

- 반대로 session 2 가 먼저 FOR UPDATE 절이 있는 커서를 실행하고, session 1 이 Update를 시도하면 해당 row가 잠겨있기 때문에 계속 대기하게 된다.

 

 

- 이 때 session 2 에서 commit 이나 rollback을 해주면, 잠금이 풀리면서 session 1 의 Update 작업이 이루어진다.

 

 

 

 

cursor_test5.sql

 DECLARE
        v_product mobile_phone.product_name%TYPE;
        v_brand mobile_phone.brand%TYPE;

 

     CURSOR cursor_mp(p_brand VARCHAR2) IS
         SELECT brand, product_name FROM mobile_phone
                WHERE brand = p_brand

         FOR UPDATE OF brand NOWAIT;


 BEGIN
        OPEN cursor_mp('LG');
        LOOP
                FETCH cursor_mp INTO v_brand, v_product;
                EXIT WHEN cursor_mp %NOTFOUND;
                DBMS_OUTPUT.PUT_LINE(v_brand || ' => ' ||  v_product);
        END LOOP;
        DBMS_OUTPUT.PUT_LINE(v_brand || ' 총 ' || cursor_mp%ROWCOUNT || ' 건');
        CLOSE cursor_mp;

 END;
 /

 

- NOWAIT를 사용한 경우이다.

- NOWAIT 는 'WAIT 0' 과 같은 의미이다. 대기 하지 않는다.

- NOWAIT 절을 사용하면 루프에서 잠금을 수행하지 못해 반환되는 오류 코드를 테스트할 수 있다.

 

 

 

 

cursor_test6.sql

 DECLARE
        v_product mobile_phone.product_name%TYPE;
        v_brand mobile_phone.brand%TYPE;

 

     CURSOR cursor_mp(p_brand VARCHAR2) IS
         SELECT brand, product_name FROM mobile_phone
                WHERE brand = p_brand

         FOR UPDATE OF brand WAIT 10;


 BEGIN
        OPEN cursor_mp('LG');
        LOOP
                FETCH cursor_mp INTO v_brand, v_product;
                EXIT WHEN cursor_mp %NOTFOUND;
                DBMS_OUTPUT.PUT_LINE(v_brand || ' => ' ||  v_product);
        END LOOP;
        DBMS_OUTPUT.PUT_LINE(v_brand || ' 총 ' || cursor_mp%ROWCOUNT || ' 건');
        CLOSE cursor_mp;

 END;
 /

 

- WAIT 에 시간(초)을 지정하면 지정한 시간동안 재시도를 하고 Lock을 획득하지 못하면 에러를 출력한다.

 

 

- 10 초 후 아래와 같은 에러를 출력한다.

 

 

 

 

###################################################################################################

#   source site : blog.naver.com/tangamjaelt

#   master : 강용운

#   email : tangamjaelt@korea.com

#   last release : 2007.08.20

###################################################################################################

 

PL/SQL에서는 일반적으로 BOOLEAN, CHAR, VARCHAR2, DATE, NUMBER 와 같은 데이터 타입을 사용하지만,

추가적으로 특정 TABLE이나 특정 COMLUMN과 같은 형식의 데이터타입을 사용할 수도 있다.

 

- 특정 TABLE의 ROW와 동일한 테이터타입 : table%ROWTYPE

- 특정 COLUMN과 동일한 데이터타입 : table.comlumn%TYPE

 

 

 

1. %ROWTYPE

 

- 프로그래밍에서 변수란 데이터를 담는 임시 그릇이다. 데이터타입을 지정한다는 것은 그릇의 크기를 메모리에 지정해주는 작업이다.

- 같은 논리로 PL/SQL에서 변수를 선언할 때 변수를 선언하고 데이터타입을 특정 테이블의 1개 ROW와 동일한 크기로 지정해서 그 곳에 값을 저장하는 것이다. C언어의 구조체와 비슷하다고 생각하면 되겠다.

 

 

예를 들어보자.

아래와 같이 brand 라는 테이블이 존재한다. (4개컬럼 : BID, BRAND_NAME, BRAND_TEL, BRAND_ADDR)

 

 

 

여기에서 1개 ROW만 뗘다가 구조를 살펴보자

 

 

 BID         BRAND_NAME   BRAND_TEL    BRAND_ADDR

--------- -------------- -------------- ------------------------
 B1           SAMSUNG       031-333-3333    경기 수원시 권선구

                                                                                

 

 

이제 brand%ROWTYPE으로 선언된 변수들는 위와 같은 1개 ROW 크기의 구조로 메모리에 잡히게 된다.

 

변수를 하나 선언해 보자.

 

 DECLARE

     brand_record   brand%ROWTYPE;

 

brand 1개 ROWTYPE 형 brand_record 변수를 선언했다.

brand_record 의 레코드의 구조는 brand 테이블의 각 필드와 동일하게 구성되므로, 아래와 같은 구조로 이루어지게 된다.

 

brand_record

 bid

 brand_name

 brand_tel

 brand_addr              

 

데이터를 담을 수 있는 공간이 한번에 4개가 생겼다.

이들 공간에 변수에 값을 넣는 작업은,

 

brand_record.bid := "100"

brand_record.brand_name := "NOKIA" 이런식으로 변수에 값 할당이 가능하다.

 

brand_record라는 변수는 생성된 메모리 공간의 첫주소를 나타내는 포인터와 같다.

 

 

보충설명

- 데이터베이스 테이블 또는 뷰의 열 collection에 따라 레코드를 선언하려면 %ROWTYPE 속성을 사용한다.

- 레코드 필드의 이름과 데이터 유형은 테이블 또는 뷰의 열에서 가져온다.

- 데이터베이스의 테이블 구조를 모르면 %ROWTYPE 속성을 사용한다.

- 테이블 유형이 변경되면 동적으로 자동 변경된다.

- 테이블에서 행 전체를 검색할 때 특히 유용하다.

 

장점

- 기본 데이터베이스 열의 수나 데이터 유형을 몰라도 사용할 수 있다.

- 실행 중에 기본 데이터베이스 열의 수나 데이터 유형을 변경할 수 있다.

- SELECT * 문을 사용하여 행(row)을 검색할 때 유용하다.

 

예제

- brand NOKIA를 추가하는 프로시저를 만들되, LG와 전화번호와 주소가 같게 작성한다.

 

 

DECLARE
    brand_new brand%ROWTYPE;
   
BEGIN
    SELECT * INTO brand_new
    FROM brand
    WHERE brand_name = 'LG';
   
    INSERT INTO brand
    VALUES ('B5','NOKIA', brand_new.brand_tel, brand_new.brand_addr);
   
    COMMIT;
END;
/

 

 

- brand_new 변수에 우선 LG의 내용을 그대로 담았다가 전화번호와 주소만 그대로 갖다 썼다.

 

 

 

추가 된 것을 확인.

 

 

 

2. %TYPE

 

- 특정 테이블의 한개 컬럼과 동일한 데이터 타입으로 변수가 생성된다.

 

예를 들면,

v_brand_name   BRAND.BRAND_NAME%TYPE := 'KTFT'

 

- brand table의 brand_name 컬럼과 같은 타입으로 지정

- brand table의 brand_name 이 변경되면 같이 변경된다.

 

개념은 동일함.

 

[본문스크랩] PL/SQL (11) - 패키지 (Package)

오라클 | 2007. 12. 21. 15:30
Posted by 시반

 ###################################################################################################

#   source site : blog.naver.com/tangamjaelt

#   master : 강용운

#   email : tangamjaelt@korea.com

#   last release : 2007.06.09

###################################################################################################

 

패키지

- 서로 관련된 스키마 오브젝트들을 묶어 캡슐화 한 것.

- 컴파일되어 스키마 오브젝트로 데이터딕셔너리에 저장된다.

- 비슷한 작업을 수행하는 프로시저, 함수 등을 함께 묶어 사용한다.

- 패키지 자체는 호출해도 사용하지 못한다. 내부의 특정 서브 프로그램(프로시저,함수 등)을 호출해야 한다.

- "패키지.서브프로그램" 형식으로 호출한다.

- 패키지 구성 : 서브 프로그램 명세(Specification) + 서브 프로그램 본문(Body)

- 패키지 명세가 바뀌면 그 패키지를 참조하는 모든 스토어드 서브 프로그램을 다시 컴파일해야 한다.

- 패키지 본문은 바뀌어도 컴파일이 필요없다.

 

 

패키지를 사용하는 이유

- 보다 효율적인 모듈 단위로 구성하여 이해하기 쉽다.

- 패키지의 public 변수와 커서는 세션이 열려 있는 동안 지속되므로 세션에서 실행되는 모든 커서와 프로시저는 공유할 수 있다.

- 여러개의 오브젝트를 한번에 메모리로 올리기 때문에 성능 향상에 도움을 준다.

- 스토어드 프로시저와 함수를 갖고 있는 라이브러리를 사용해서 코드 재사용을 증진시켜 불필요한 코딩을 줄인다.

 

 

패키지 명세

- 패키지의 이름과 인수의 이름, 데이터형을 public으로 선언하는 부분.

- 패키지에 선언된 오브젝트는 패키지 어디에서나 접근 가능하다. (패키지에 대해 전역적)

- 응용 프로그램이 스토어드 서브 프로그램을 실행해야 하는 모든 정보는 패키지 명세에 들어 있다.

- 즉, 패키지 내에 어떤 오브젝트들이 있는지 미리 이름과 형식을 알리는 것임.

*******************************************************************************************************************

CREATE [OR REPLACE] PACKAGE 패키지이름

[AUTHID {CURRENT_USER | DEFINER} {IS | AS}

[패키지 본문 오브젝트 선언]

END 패키지이름;

*******************************************************************************************************************

- AUTHID : 패키지 실행시 호출할 권한의 유형.

       - CURRENT_USER : 현재 사용자(호출자)

       - DEFINER : 생성자

- 패키지 본문 오브젝트 선언 : 패키지에서 생성될 오브젝트의 목록을 적는 부분

 

 

패키지 본문

- 패키지 본문에는 명세에서 선언한 실제 오브젝트의 코드가 들어간다.

*******************************************************************************************************************

CREATE [OR REPLACE] PACKAGE BODY 패키지이름 {IS | AS}

   [패키지 본문 오브젝트 선언]

BEGIN

   프로그램문장

END 패키지이름;

*******************************************************************************************************************

 

패키지 서브 프로그램 호출

1. 사용자가 서브 프로그램에 대한 실행 권한을 가지고 있는지 확인한다.

2. Dictionary View에서 프로시저가 VALID 상태인지 확인한다. INVALID 라면 실행 전에 자동으로 재컴파일한다.

3. 패키지의 서브 프로그램을 실행한다.

4. 점(.)으로 패키지와 서브 프로그램을 구분하여 사용한다.

    - 패키지.형

    - 패키지.오브젝트

    - 패키지.서브프로그램

 

 

 

[예제1] id10 의 나이와 마일리지를 변경하는 프로시저를 포함하는 패키지 작성

 

1. 아래처럼 USERID 가 'id10' 인 홍길동이 있다.

 

 

 

2. 패키지 명세를 작성하고 실행한다. (패키지 이름 : change_pkg)

********************************************************************************************************************

CREATE OR REPLACE PACKAGE change_pkg AS
  PROCEDURE change_ages (i_id IN VARCHAR2);
  PROCEDURE change_mileage (i_id IN VARCHAR2);
END change_pkg;
/
********************************************************************************************************************

 

 

3. 패키지 몸체(Body)를 작성하고 실행시킨다. (change_ages, change_mileage)

********************************************************************************************************************

CREATE OR REPLACE PACKAGE BODY change_pkg AS

        i_id VARCHAR2(10);

 

PROCEDURE change_ages (i_id IN VARCHAR2) IS
BEGIN
        UPDATE member
        SET AGE=100
        WHERE userid = i_id;
END change_ages;

 

PROCEDURE change_mileage (i_id IN VARCHAR2) IS
BEGIN
        UPDATE member
        SET MILEAGE=777
        WHERE userid = i_id;
END change_mileage;

END change_pkg;
/
********************************************************************************************************************

 

 

4. 패키지의 프로시저를 실행시킨다.

SQL> exec change_pkg.change_ages('id10');

SQL> exec change_pkg.change_mileage('id10');

 

 

###################################################################################################

#   source site : blog.naver.com/tangamjaelt

#   master : 강용운

#   email : tangamjaelt@korea.com

#   last release : 2007.06.03

###################################################################################################

 

프로시저 (procedure) 와 패키지 (package)

- 프로그램 유지 보수와 실행을 보다 쉽게 하기 위해서 프로그램 코드를 논리적으로 구성한 것.

- 1개 패키지 내에 여러개의 프로시저가 존재한다.

 

스토어드 프로시저 (stored procedure)

- 데이터베이스 내에 컴파일되어 저장된 프로시저.

- 데이터베이스에 저장된 프로시저는 오브젝트로 관리된다.

 

프로시저를 사용하는 이유

- 특정 문제나 작업을 해결하기 위해서 사용한다.

- 특정 기능을 담당하는 모듈(module) 단위로 되어 있다.

- 재사용이 가능하다.

- 스토어드 프로시저를 통해서만 데이터를 액세스할 수 있어 보안이 향상된다.

- 프로시저는 공유된 메모리 자원을 이용한다.

 

프로시저와 함수

- 둘은 출력의 형식이 다르다.

- 프로시저 : 많은 양의 정보를 처리한다.

- 함수 : 하나의 값을 Return 한다.

 

프로시저 생성

- 프로시저를 생성할 때 오라클은 컴파일하는 동안 접근하는 오브젝트(Table,View 등)가 존재하는지 검사하고, 접근 권한이 있는지를 검사한다.

********************************************************************************************************************

CREATE OR REPLACE PROCEDURE 프로시저이름 (IN/OUT/INOUT)

AS

     PL/SQL 본문코드

END 프로시저이름

********************************************************************************************************************

- OR REPLACE : 프로시저가 이미 존재할 경우 덮어 쓴다. 항상 사용하는 것이 좋다.

- IN : 호출되는 프로시저에 값을 전달한다는 것을 지정

- OUT : 프로시저를 호출한 프로그램에게 값을 반환한다는 것을 지정

- INOUT : IN + OUT. 프로시저에 값을 전달하고 결과를 프로그램에게 반환한다는 것을 지정.

 

RETURN 문

- 프로시저가 끝나기 전에 마칠 경우에만 사용한다.

 

컴파일 / 재컴파일

- 스토어드 프로시저를 명시적으로 재컴파일 하려면 ALTER PROCEDURE 명령을 사용한다.

- ALTER PROCEDURE 는 패키지 내에 있는 프로시저가 아닌 독립된 프로시저에서만 사용 가능하다.

- 프로시저가 컴파일되면, 다음 실행시 컴파일 할 필요가 없어 부하를 줄일 수 있고, 컴파일 오류를 제거할 수 있다.

- 오라클은 부모 오브젝트가 명시적으로 다시 컴파일될 때 종속된 모든 오브젝트를 자동으로 재컴파일 한다. 따라서 부모 오브젝트를 컴파일 할 경우 관련된 모든 오브젝트가 모두 다시 컴파일이 일어나므로 시스템에 부하를 줄 수 있다.

 

프로시저 실행

- execute 명령으로 스토어드 프로시저를 실행할 수 있다.

 

[예제1]  사용자가 지정한 나이를 가진 사람의 나이를 100 으로 변경하는 스토어드 프로시저

********************************************************************************************************************

CREATE OR REPLACE PROCEDURE change_ages (i_age IN integer)
AS
BEGIN
        UPDATE member
        SET AGE=100
        WHERE age = i_age;
END change_ages;
/
********************************************************************************************************************

 

 

- 프로시저 실행

 

 

- 결과 확인 (62  -> 100 살로 변경)

 

 

 

파라미터

- 프로시저는 파라미터를 사용하여 정보를 전달한다.

- 프로시저를 호출할 때는 프로시저의 파라미터에 대해 값을 전달해야 한다.

- Actual Parameter : 프로시저에 전달된 파라미터 (실제 파라미터)

- Internal or Formal Parameter : 프로시저 내부에 선언된 파라미터 (내부 또는 형식 파라미터)

- Actual Parameter 의 데이터형과 Internal Parameter 의 데이터형이 같아야 한다.

 

 

스토어드 프로시저 확인

- 스토어드 프로시저에 관한 정보를 제공하는 데이터 딕셔너리 뷰

 

ALL_ERRORS : 현재 사용자가 액세스 가능한 모든 오브젝트에 대한 오류 목록

ALL_SOURCE : 현재 사용자가 액세스 가능한 모든 오브젝트의 텍스트 소스

 

USER_OBJECTS : 현재 사용자가 액세스 가능한 모든 오브젝토 목록

USER_ERRORS : 현재 사용자에게 속한 오브젝트의 오류 목록

USER_OBJECT_SIZE : 현재 사용자의 모든 PL/SQL 오브젝트

USER_SOURCE : 현재 사용자에게 속한 모든 오브젝트의 텍스트 소스

 

DBA_OBJECTS : 데이터베이스에 저장된 모든 오브젝트 목록

DBA_ERRORS : 데이터베이스에 저장된 모든 오브젝트에 대한 오류 목록

DBA_OBJECT_SIZE : 데이터베이스에 있는 모든 PL/SQL 오브젝트

DBA_SOURCE : 데이터베이스 전체에 대한 정보

 

- 어떤 오브젝트가 INVALID 상태인지 확인하고 다시 컴파일 할 필요가 있는지 확인할 수 있다.

- INVALID 인 함수나 프로시저는 잘못된 구문이 있을 수 있다.

 

SQL> select object_name, object_type, status from user_objects where status = 'INVALID';

 

 

 

프로시저 삭제

DROP PROCEDURE 프로시저이름;

 

프로시저 오버로딩

- 한 패키지에서 동일한 이름의 프로시저에 각각 다른 인수를 사용해서 호출할 수 있다.

- 서로 다른 데이터형을 갖고 있는 인수를 가지고 동일한 프로시저를 여러 번 실행해야할 경우 유용하다.

 

재귀 프로시저

- 자기 자신을 호출하는 프로시저

 
 

[본문스크랩] PL/SQL (9) - 변환 함수 사용

오라클 | 2007. 12. 21. 15:29
Posted by 시반

###################################################################################################

#   source site : blog.naver.com/tangamjaelt

#   master : 강용운

#   email : tangamjaelt@korea.com

#   last release : 2007.05.28

###################################################################################################

 

1. 변환 함수

- 함수 중에서 가장 널리 사용하고 중요한 함수이다.

- 다른 데이터형으로 변환시킨다.

 

 

2. TO_DATE

- TO_DATE(문자스트링, 서식, NLS_DATE_LANGUAGE)

- 서식을 지정하지 않으면 기본 DATE 형식인 DD-MMM-YY 가 적용된다.

- 변환될 문자는 220자를 넘을 수 없다.

- 12시간제 / 24시간제 중 하나를 선택한다.

- 대표 변환마스크.

MM : 01~12로 월 표시.

MONTH : 월 이름을 9자리 문자로 할당. 나머지 문자는 공백.

MON : 월 이름을 3자리 문자로

D : 1주를 1일~7일

DD : 1달을 1일~31일

DDD : 1년을 1일~365일

DAY : 요일을 철자대로 표기하는 것. 항상 9자리를 차지. 남는 오른쪽 자리는 공백으로

HH, HH12 : 하루를 1~12까지의 시간으로 나타냄

HH24 : 하루를 0~23까지의 시간으로 나타냄

MI : 1시간을 0~59분까지 나타냄

SS : 1분을 0~59초까지 나타냄

SSSS : 자정부터 지난 시간을 모두 초단위로 계산한다.

 

 

3. TO_CHAR

- 숫자나 날짜를 문자로 변환한다.

- 날짜의 형식을 기본형식인 DD-MMM-YY 와 다르게 출력하고자 할 때.

- MONTH, Month, month => MAY, May, may

 

 

4. TO_NUMBER

- 문자를 숫자로 변환한다.

- 문자로 저장되어 있는 입사일 기준으로 근속년수를 계산한다고 하면, 입사일을 TO_NUMBER로 변환하여 계산해야 한다.

- 너무 자주 사용되는 곳에는 변환 과정에서 시스템 부하를 줄 수 있다.

- 대표 변환 마스크

9 : 각 9는 의미있는 자리로 간주됨. 앞에 나오는 0은 공백으로 취급.

0 : 숫자 앞이나 뒤에 0이 있을 경우, 0을 취급하기 위함. 09999, 99990

$ : 통화표시. $9999

B : 정수가 0이 아니면 정수의 일부를 공백으로 반환한다. 이 서식에 0을 사용하면 앞에 오는 0은 무시된다. B9999

MI : 값이 음수이면 '-'부호 갖고, 값이 양수이면 끝에 공백을 갖는다. 9999MI

S : 음수면 '-', 양수면 '+' 부호를 갖는다. S9999, 9999S

PR : 음수면 < > 로 묶고, 양수면 공백 추가. 9999PR

D : 소수점 위치 지정. 99D99

G : 분리자를 지정(,) 9G999G999

C : 지정한 위치에 ISO 통화기호를 반환한다. C99

L : 지역 통화기호를 반환한다. L9999

, : 지정한 위치에 콤마 삽입. 9,999,9999

. : 그룹 분리자에 관계 없이 소수점의 위치를 지정. 99.99

V : 10의 n 승. V뒤에 숫자가 10을 곱할 갯수. 999V99

EEEE : 지수 표시. 9.99EEEE

RM, rm : 값을 대문자,소문자로 된 로마숫자로 표시

FM : 앞과 뒤의 공백을 제거. FM9,999.99

 

 

5. Sample

 

SQL> select TO_DATE('070528','MMDDYY') "Today" from dual;

Today
---------
05-JUL-28

 

SQL> select TO_DATE('March 30', 'MONTH DD') from dual;

TO_DATE('
---------
30-MAR-07


 

SQL> select TO_DATE('28-DEC-82') "Birthday" from dual;

Birthday
---------
28-DEC-82

 

SQL> select TO_DATE('070528','YYMMDD')+3 from dual;

TO_DATE('
---------
31-MAY-07


 

SQL> select TO_CHAR(SYSDATE, 'MONTH DDTH YYYY') "Now" from dual;

Now
-----------------------
MAY       28TH 2007        ☞ MONTH → 9자리 채움.

 

SQL> select TO_CHAR(SYSDATE, 'Month DD, Y,YYY') from dual;

TO_CHAR(SYSDATE,'MONTHD
-----------------------
May       28, 2,007

 

SQL> select TO_CHAR(SYSDATE, 'YYYY-MM-DD') "Now" from dual;

Now
----------
2007-05-28

 

SQL> select TO_CHAR(SYSDATE, 'YYYY-MM-DD', 'NLS_DATE_LANGUAGE=german') "German" from dual;

German

----------
2007-05-28


SQL> select TO_CHAR(SYSDATE, 'YYYY-MM-DD', 'NLS_DATE_LANGUAGE=korean') "Korean" from dual;

Korean
----------
2007-05-28


 

SQL> select TO_NUMBER('100.00', '9G999D99') from dual;

TO_NUMBER('100.00','9G999D99')
------------------------------
                                        100

 

문자 => 숫자변환 후 100으로 나누는 코드

 

[본문스크랩] PL/SQL (8) - 오라클 내장 함수

오라클 | 2007. 12. 21. 15:29
Posted by 시반

###################################################################################################

#   source site : blog.naver.com/tangamjaelt

#   master : 강용운

#   email : tangamjaelt@korea.com

#   last release : 2007.05.28

###################################################################################################

 

1. 오라클 내장 함수

- 오라클에서 제공하는 함수가 있기 때문에 이를 사용하여 불필요한 수고를 덜 수 있다.

- 프로그래밍 언어의 명령, 함수, 구문, 사용법 등을 알고 이런 강력한 기능들을 사용하는 것도 능력이다.

- 종류 : 문자, 숫자, 날짜, 변환, 집합, 기타 함수

- 결과를 확인하고자 할 경우 DUAL table을 사용한다.

 

  * 함수의 분류와 모든 목록
    http://download-east.oracle.com/docs/cd/B19306_01/server.102/b14200/functions001.htm#i88893

 

 

SQL Functions

SQL functions are built into Oracle Database and are available for use in various appropriate SQL statements. Do not confuse SQL functions with user-defined functions written in PL/SQL.

If you call a SQL function with an argument of a datatype other than the datatype expected by the SQL function, then Oracle attempts to convert the argument to the expected datatype before performing the SQL function. If you call a SQL function with a null argument, then the SQL function automatically returns null. The only SQL functions that do not necessarily follow this behavior are CONCAT, NVL, REPLACE, and REGEXP_REPLACE.

Note:

The combined values of the NLS_COMP and NLS_SORT settings determine the rules by which characters are sorted and compared. If NLS_COMP is set to LINGUISTIC for your database, then all entities in this chapter will be interpreted according to the rules specified by the NLS_SORT parameter. If NLS_COMP is not set to LINGUISTIC, then the functions are interpreted without regard to the NLS_SORT setting. NLS_SORT can be explicitly set. If it is not set explicitly, it is derived from NLS_LANGUAGE. Please refer to Oracle Database Globalization Support Guide for more information on these settings.

In the syntax diagrams for SQL functions, arguments are indicated by their datatypes. When the parameter function appears in SQL syntax, replace it with one of the functions described in this section. Functions are grouped by the datatypes of their arguments and their return values.

Note:

When you apply SQL functions to LOB columns, Oracle Database creates temporary LOBs during SQL and PL/SQL processing. You should ensure that temporary tablespace quota is sufficient for storing these temporary LOBs for your application.

See Also:

The syntax showing the categories of functions follows:

function::=


Description of the illustration function.gif

single_row_function::=


Description of the illustration single_row_function.gif

The sections that follow list the built-in SQL functions in each of the groups illustrated in the preceding diagrams except user-defined functions. All of the built-in SQL functions are then described in alphabetical order.

Single-Row Functions

Single-row functions return a single result row for every row of a queried table or view. These functions can appear in select lists, WHERE clauses, START WITH and CONNECT BY clauses, and HAVING clauses.

Numeric Functions

Numeric functions accept numeric input and return numeric values. Most numeric functions that return NUMBER values that are accurate to 38 decimal digits. The transcendental functions COS, COSH, EXP, LN, LOG, SIN, SINH, SQRT, TAN, and TANH are accurate to 36 decimal digits. The transcendental functions ACOS, ASIN, ATAN, and ATAN2 are accurate to 30 decimal digits. The numeric functions are:


ABS
ACOS
ASIN
ATAN
ATAN2
BITAND
CEIL
COS
COSH
EXP
FLOOR
LN
LOG
MOD
NANVL
POWER
REMAINDER
ROUND (number)
SIGN
SIN
SINH
SQRT
TAN
TANH
TRUNC (number)
WIDTH_BUCKET

Character Functions Returning Character Values

Character functions that return character values return values of the following datatypes unless otherwise documented:

  • If the input argument is CHAR or VARCHAR2, then the value returned is VARCHAR2.

  • If the input argument is NCHAR or NVARCHAR2, then the value returned is NVARCHAR2.

The length of the value returned by the function is limited by the maximum length of the datatype returned.

  • For functions that return CHAR or VARCHAR2, if the length of the return value exceeds the limit, then Oracle Database truncates it and returns the result without an error message.

  • For functions that return CLOB values, if the length of the return values exceeds the limit, then Oracle raises an error and returns no data.

The character functions that return character values are:


CHR
CONCAT
INITCAP
LOWER
LPAD
LTRIM
NLS_INITCAP
NLS_LOWER
NLSSORT
NLS_UPPER
REGEXP_REPLACE
REGEXP_SUBSTR
REPLACE
RPAD
RTRIM
SOUNDEX
SUBSTR
TRANSLATE
TREAT
TRIM
UPPER

NLS Character Functions

The NLS character functions return information about the character set. The NLS character functions are:


NLS_CHARSET_DECL_LEN
NLS_CHARSET_ID
NLS_CHARSET_NAME

Character Functions Returning Number Values

Character functions that return number values can take as their argument any character datatype.

The character functions that return number values are:


ASCII
INSTR
LENGTH
REGEXP_INSTR

Datetime Functions

Datetime functions operate on date (DATE), timestamp (TIMESTAMP, TIMESTAMP WITH TIME ZONE, and TIMESTAMP WITH LOCAL TIME ZONE), and interval (INTERVAL DAY TO SECOND, INTERVAL YEAR TO MONTH) values.

Some of the datetime functions were designed for the Oracle DATE datatype (ADD_MONTHS, CURRENT_DATE, LAST_DAY, NEW_TIME, and NEXT_DAY). If you provide a timestamp value as their argument, Oracle Database internally converts the input type to a DATE value and returns a DATE value. The exceptions are the MONTHS_BETWEEN function, which returns a number, and the ROUND and TRUNC functions, which do not accept timestamp or interval values at all.

The remaining datetime functions were designed to accept any of the three types of data (date, timestamp, and interval) and to return a value of one of these types.

The datetime functions are:


ADD_MONTHS
CURRENT_DATE
CURRENT_TIMESTAMP
DBTIMEZONE
EXTRACT (datetime)
FROM_TZ
LAST_DAY
LOCALTIMESTAMP
MONTHS_BETWEEN
NEW_TIME
NEXT_DAY
NUMTODSINTERVAL
NUMTOYMINTERVAL
ROUND (date)
SESSIONTIMEZONE
SYS_EXTRACT_UTC
SYSDATE
SYSTIMESTAMP
TO_CHAR (datetime)
TO_TIMESTAMP
TO_TIMESTAMP_TZ
TO_DSINTERVAL
TO_YMINTERVAL
TRUNC (date)
TZ_OFFSET

General Comparison Functions

The general comparison functions determine the greatest and or least value from a set of values. The general comparison functions are:


GREATEST
LEAST

Conversion Functions

Conversion functions convert a value from one datatype to another. Generally, the form of the function names follows the convention datatype TO datatype. The first datatype is the input datatype. The second datatype is the output datatype. The SQL conversion functions are:


ASCIISTR
BIN_TO_NUM
CAST
CHARTOROWID
COMPOSE
CONVERT
DECOMPOSE
HEXTORAW
NUMTODSINTERVAL
NUMTOYMINTERVAL
RAWTOHEX
RAWTONHEX
ROWIDTOCHAR
ROWIDTONCHAR
SCN_TO_TIMESTAMP
TIMESTAMP_TO_SCN
TO_BINARY_DOUBLE
TO_BINARY_FLOAT
TO_CHAR (character)
TO_CHAR (datetime)
TO_CHAR (number)
TO_CLOB
TO_DATE
TO_DSINTERVAL
TO_LOB
TO_MULTI_BYTE
TO_NCHAR (character)
TO_NCHAR (datetime)
TO_NCHAR (number)
TO_NCLOB
TO_NUMBER
TO_DSINTERVAL
TO_SINGLE_BYTE
TO_TIMESTAMP
TO_TIMESTAMP_TZ
TO_YMINTERVAL
TO_YMINTERVAL
TRANSLATE ... USING
UNISTR

Large Object Functions

The large object functions operate on LOBs. The large object functions are:


BFILENAME
EMPTY_BLOB, EMPTY_CLOB

Collection Functions

The collection functions operate on nested tables and varrays. The SQL collection functions are:


CARDINALITY
COLLECT
POWERMULTISET
POWERMULTISET_BY_CARDINALITY
SET

Hierarchical Function

The hierarchical function applies hierarchical path information to a result set.


SYS_CONNECT_BY_PATH

Data Mining Functions

The data mining functions operate on models that have been built using the DBMS_DATA_MINING package or the Oracle Data Mining Java API. The SQL data mining functions are:


CLUSTER_ID
CLUSTER_PROBABILITY
CLUSTER_SET
FEATURE_ID
FEATURE_SET
FEATURE_VALUE
PREDICTION
PREDICTION_COST
PREDICTION_DETAILS
PREDICTION_PROBABILITY
PREDICTION_SET

XML Functions

The XML functions operate on or return XML documents or fragments. For more information about selecting and querying XML data using these functions, including information on formatting output, please refer to Oracle XML DB Developer's Guide. The SQL XML functions are:


APPENDCHILDXML
DELETEXML
DEPTH
EXTRACT (XML)
EXISTSNODE
EXTRACTVALUE
INSERTCHILDXML
INSERTXMLBEFORE
PATH
SYS_DBURIGEN
SYS_XMLAGG
SYS_XMLGEN
UPDATEXML
XMLAGG
XMLCDATA
XMLCOLATTVAL
XMLCOMMENT
XMLCONCAT
XMLFOREST
XMLPARSE
XMLPI
XMLQUERY
XMLROOT
XMLSEQUENCE
XMLSERIALIZE
XMLTABLE
XMLTRANSFORM

Encoding and Decoding Functions

The encoding and decoding functions let you inspect and decode data in the database.


DECODE
DUMP
ORA_HASH
VSIZE

NULL-Related Functions

The NULL-related functions facilitate null handling. The NULL-related functions are:


COALESCE
LNNVL
NULLIF
NVL
NVL2

Environment and Identifier Functions

The environment and identifier functions provide information about the instance and session. These functions are:


SYS_CONTEXT
SYS_GUID
SYS_TYPEID
UID
USER
USERENV

Aggregate Functions

Aggregate functions return a single result row based on groups of rows, rather than on single rows. Aggregate functions can appear in select lists and in ORDER BY and HAVING clauses. They are commonly used with the GROUP BY clause in a SELECT statement, where Oracle Database divides the rows of a queried table or view into groups. In a query containing a GROUP BY clause, the elements of the select list can be aggregate functions, GROUP BY expressions, constants, or expressions involving one of these. Oracle applies the aggregate functions to each group of rows and returns a single result row for each group.

If you omit the GROUP BY clause, then Oracle applies aggregate functions in the select list to all the rows in the queried table or view. You use aggregate functions in the HAVING clause to eliminate groups from the output based on the results of the aggregate functions, rather than on the values of the individual rows of the queried table or view.

See Also:

"Using the GROUP BY Clause: Examples" and the "HAVING Clause" for more information on the GROUP BY clause and HAVING clauses in queries and subqueries

Many (but not all) aggregate functions that take a single argument accept these clauses:

  • DISTINCT causes an aggregate function to consider only distinct values of the argument expression.

  • ALL causes an aggregate function to consider all values, including all duplicates.

For example, the DISTINCT average of 1, 1, 1, and 3 is 2. The ALL average is 1.5. If you specify neither, then the default is ALL.

All aggregate functions except COUNT(*) and GROUPING ignore nulls. You can use the NVL function in the argument to an aggregate function to substitute a value for a null. COUNT never returns null, but returns either a number or zero. For all the remaining aggregate functions, if the data set contains no rows, or contains only rows with nulls as arguments to the aggregate function, then the function returns null.

The aggregate functions MIN, MAX, SUM, AVG, COUNT, VARIANCE, and STDDEV, when followed by the KEEP keyword, can be used in conjunction with the FIRST or LAST function to operate on a set of values from a set of rows that rank as the FIRST or LAST with respect to a given sorting specification. Please refer to FIRST for more information.

You can nest aggregate functions. For example, the following example calculates the average of the maximum salaries of all the departments in the sample schema hr:

SELECT AVG(MAX(salary)) FROM employees GROUP BY department_id;

AVG(MAX(SALARY))
----------------
           10925

This calculation evaluates the inner aggregate (MAX(salary)) for each group defined by the GROUP BY clause (department_id), and aggregates the results again.

The aggregate functions are:


AVG
COLLECT
CORR
CORR_*
COUNT
COVAR_POP
COVAR_SAMP
CUME_DIST
DENSE_RANK
FIRST
GROUP_ID
GROUPING
GROUPING_ID
LAST
MAX
MEDIAN
MIN
PERCENTILE_CONT
PERCENTILE_DISC
PERCENT_RANK
RANK
REGR_ (Linear Regression) Functions
STATS_BINOMIAL_TEST
STATS_CROSSTAB
STATS_F_TEST
STATS_KS_TEST
STATS_MODE
STATS_MW_TEST
STATS_ONE_WAY_ANOVA
STATS_T_TEST_*
STATS_WSR_TEST
STDDEV
STDDEV_POP
STDDEV_SAMP
SUM
VAR_POP
VAR_SAMP
VARIANCE

Analytic Functions

Analytic functions compute an aggregate value based on a group of rows. They differ from aggregate functions in that they return multiple rows for each group. The group of rows is called a window and is defined by the analytic_clause. For each row, a sliding window of rows is defined. The window determines the range of rows used to perform the calculations for the current row. Window sizes can be based on either a physical number of rows or a logical interval such as time.

Analytic functions are the last set of operations performed in a query except for the final ORDER BY clause. All joins and all WHERE, GROUP BY, and HAVING clauses are completed before the analytic functions are processed. Therefore, analytic functions can appear only in the select list or ORDER BY clause.

Analytic functions are commonly used to compute cumulative, moving, centered, and reporting aggregates.

analytic_function::=


Description of the illustration analytic_function.gif

analytic_clause::=


Description of the illustration analytic_clause.gif

query_partition_clause::=


Description of the illustration query_partition_clause.gif

order_by_clause::=


Description of the illustration order_by_clause.gif

windowing_clause ::=


Description of the illustration windowing_clause.gif

The semantics of this syntax are discussed in the sections that follow.

analytic_function

Specify the name of an analytic function (see the listing of analytic functions following this discussion of semantics).

arguments

Analytic functions take 0 to 3 arguments. The arguments can be any numeric datatype or any nonnumeric datatype that can be implicitly converted to a numeric datatype. Oracle determines the argument with the highest numeric precedence and implicitly converts the remaining arguments to that datatype. The return type is also that datatype, unless otherwise noted for an individual function.

See Also:

"Numeric Precedence" for information on numeric precedence and Table 2-10, "Implicit Type Conversion Matrix" for more information on implicit conversion

analytic_clause

Use OVER analytic_clause to indicate that the function operates on a query result set. That is, it is computed after the FROM, WHERE, GROUP BY, and HAVING clauses. You can specify analytic functions with this clause in the select list or ORDER BY clause. To filter the results of a query based on an analytic function, nest these functions within the parent query, and then filter the results of the nested subquery.

Notes on the analytic_clauseThe following notes apply to the analytic_clause:

  • You cannot specify any analytic function in any part of the analytic_clause. That is, you cannot nest analytic functions. However, you can specify an analytic function in a subquery and compute another analytic function over it.

  • You can specify OVER analytic_clause with user-defined analytic functions as well as built-in analytic functions. See CREATE FUNCTION.

query_partition_clause

Use the PARTITION BY clause to partition the query result set into groups based on one or more value_expr. If you omit this clause, then the function treats all rows of the query result set as a single group.

To use the query_partition_clause in an analytic function, use the upper branch of the syntax (without parentheses). To use this clause in a model query (in the model_column_clauses) or a partitioned outer join (in the outer_join_clause), use the lower branch of the syntax (with parentheses).

You can specify multiple analytic functions in the same query, each with the same or different PARTITION BY keys.

If the objects being queried have the parallel attribute, and if you specify an analytic function with the query_partition_clause, then the function computations are parallelized as well.

Valid values of value_expr are constants, columns, nonanalytic functions, function expressions, or expressions involving any of these.

order_by_clause

Use the order_by_clause to specify how data is ordered within a partition. For all analytic functions except PERCENTILE_CONT and PERCENTILE_DISC (which take only a single key), you can order the values in a partition on multiple keys, each defined by a value_expr and each qualified by an ordering sequence.

Within each function, you can specify multiple ordering expressions. Doing so is especially useful when using functions that rank values, because the second expression can resolve ties between identical values for the first expression.

Whenever the order_by_clause results in identical values for multiple rows, the function returns the same result for each of those rows. Please refer to the analytic example for SUM for an illustration of this behavior.

Restrictions on the ORDER BY Clause The following restrictions apply to the ORDER BY clause:

  • When used in an analytic function, the order_by_clause must take an expression (expr). The SIBLINGS keyword is not valid (it is relevant only in hierarchical queries). Position (position) and column aliases (c_alias) are also invalid. Otherwise this order_by_clause is the same as that used to order the overall query or subquery.

  • An analytic function that uses the RANGE keyword can use multiple sort keys in its ORDER BY clause if it specifies either of these two windows:

    • RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. The short form of this is RANGE UNBOUNDED PRECEDING.

    • RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING. The short form of this is RANGE UNBOUNDED FOLLOWING.

    Window boundaries other than these two can have only one sort key in the ORDER BY clause of the analytic function. This restriction does not apply to window boundaries specified by the ROW keyword.

ASC | DESC Specify the ordering sequence (ascending or descending). ASC is the default.

NULLS FIRST | NULLS LAST Specify whether returned rows containing nulls should appear first or last in the ordering sequence.

NULLS LAST is the default for ascending order, and NULLS FIRST is the default for descending order.

Analytic functions always operate on rows in the order specified in the order_by_clause of the function. However, the order_by_clause of the function does not guarantee the order of the result. Use the order_by_clause of the query to guarantee the final result ordering.

See Also:

order_by_clause of SELECT for more information on this clause

windowing_clause

Some analytic functions allow the windowing_clause. In the listing of analytic functions at the end of this section, the functions that allow the windowing_clause are followed by an asterisk (*).

ROWS | RANGE These keywords define for each row a window (a physical or logical set of rows) used for calculating the function result. The function is then applied to all the rows in the window. The window moves through the query result set or partition from top to bottom.

  • ROWS specifies the window in physical units (rows).

  • RANGE specifies the window as a logical offset.

You cannot specify this clause unless you have specified the order_by_clause. Some window boundaries defined by the RANGE clause let you specify only one expression in the order_by_clause. Please refer to "Restrictions on the ORDER BY Clause".

The value returned by an analytic function with a logical offset is always deterministic. However, the value returned by an analytic function with a physical offset may produce nondeterministic results unless the ordering expression results in a unique ordering. You may have to specify multiple columns in the order_by_clause to achieve this unique ordering.

BETWEEN ... AND Use the BETWEEN ... AND clause to specify a start point and end point for the window. The first expression (before AND) defines the start point and the second expression (after AND) defines the end point.

If you omit BETWEEN and specify only one end point, then Oracle considers it the start point, and the end point defaults to the current row.

UNBOUNDED PRECEDING Specify UNBOUNDED PRECEDING to indicate that the window starts at the first row of the partition. This is the start point specification and cannot be used as an end point specification.

UNBOUNDED FOLLOWING Specify UNBOUNDED FOLLOWING to indicate that the window ends at the last row of the partition. This is the end point specification and cannot be used as a start point specification.

CURRENT ROW As a start point, CURRENT ROW specifies that the window begins at the current row or value (depending on whether you have specified ROW or RANGE, respectively). In this case the end point cannot be value_expr PRECEDING.

As an end point, CURRENT ROW specifies that the window ends at the current row or value (depending on whether you have specified ROW or RANGE, respectively). In this case the start point cannot be value_expr FOLLOWING.

value_expr PRECEDING or value_expr FOLLOWING For RANGE or ROW:

  • If value_expr FOLLOWING is the start point, then the end point must be value_expr FOLLOWING.

  • If value_expr PRECEDING is the end point, then the start point must be value_expr PRECEDING.

If you are defining a logical window defined by an interval of time in numeric format, then you may need to use conversion functions.

See Also:

NUMTOYMINTERVAL and NUMTODSINTERVAL for information on converting numeric times into intervals

If you specified ROWS:

  • value_expr is a physical offset. It must be a constant or expression and must evaluate to a positive numeric value.

  • If value_expr is part of the start point, then it must evaluate to a row before the end point.

If you specified RANGE:

  • value_expr is a logical offset. It must be a constant or expression that evaluates to a positive numeric value or an interval literal. Please refer to "Literals" for information on interval literals.

  • You can specify only one expression in the order_by_clause

  • If value_expr evaluates to a numeric value, then the ORDER BY expr must be a numeric or DATE datatype.

  • If value_expr evaluates to an interval value, then the ORDER BY expr must be a DATE datatype.

If you omit the windowing_clause entirely, then the default is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW.

Analytic functions are commonly used in data warehousing environments. In the list of analytic functions that follows, functions followed by an asterisk (*) allow the full syntax, including the windowing_clause.


AVG *
CORR *
COVAR_POP *
COVAR_SAMP *
COUNT *
CUME_DIST
DENSE_RANK
FIRST
FIRST_VALUE *
LAG
LAST
LAST_VALUE *
LEAD
MAX *
MIN *
NTILE
PERCENT_RANK
PERCENTILE_CONT
PERCENTILE_DISC
RANK
RATIO_TO_REPORT
REGR_ (Linear Regression) Functions *
ROW_NUMBER
STDDEV *
STDDEV_POP *
STDDEV_SAMP *
SUM *
VAR_POP *
VAR_SAMP *
VARIANCE *

See Also:

Oracle Data Warehousing Guide for more information on these functions and for scenarios illustrating their use

Object Reference Functions

Object reference functions manipulate REF values, which are references to objects of specified object types. The object reference functions are:


DEREF
MAKE_REF
REF
REFTOHEX
VALUE

See Also:

Oracle Database Concepts for more information about REF datatypes

Model Functions

Model functions can be used only in the model_clause of the SELECT statement. The model functions are:


CV
ITERATION_NUMBER
PRESENTNNV
PRESENTV
PREVIOUS
 

[본문스크랩] PL/SQL (7) - 조건문 사용

오라클 | 2007. 12. 21. 15:28
Posted by 시반

###################################################################################################

#   source site : blog.naver.com/tangamjaelt

#   master : 강용운

#   email : tangamjaelt@korea.com

#   last release : 2007.05.28

###################################################################################################

 

1. IF 문

**********************************************************************************************************************

IF (조건)

THEN

     (조건이 참일 경우 수행)

ELSE

     (조건이 참이 아닐 경우 수행)

END IF;

**********************************************************************************************************************

 

 

2. 중첩 IF 문

**********************************************************************************************************************

IF (조건1)

THEN

     IF (조건2)

     THEN

            (조건1,2 모두 참일 경우 실행)

     ELSE 

           IF (조건3) 

           THEN

                 (조건1,2 참이 아니고, 조건3 이 참일 경우 실행)

            ELSE

                 (조건1,2,3 모두 거짓일 경우 실행)

            END IF;

      END IF;

END IF;

**********************************************************************************************************************

- 중첩 IF 문은 어쨌든 IF...THEN...END IF 형태만 유지하면서 늘려가면 된다.

- 이것을 보기좋게 줄인 것이 IF...ELSIF 이다.

 

 

3. IF... ELSIF 문

**********************************************************************************************************************

IF (조건1)

THEN

     (조건1 이 참일 경우 실행)     

ELSIF (조건2)

THEN

      (조건2 가 참일 경우 실행)

ELSIF (조건3)

THEN

      (조건3 이 참일 경우 실행)

ELSE

      (아무것도 아닐 때 실행)

END IF;

**********************************************************************************************************************

- IF 와 END IF 는 딱 한번만 사용되고, 중간은 모두 ELSIF..THEN으로 계속해서 조건을 추가할 수 있다.

- ELSE IF 가 아닌 ELSIF 이다.

- 조건에 대한 주석을 달면 알아보기 쉽다.  (주석은 '/*...*/' 또는 '--'  사용)

 

 

[예제1] IF...ELSIF 문 사용

**********************************************************************************************************************

DECLARE
        v_Score NUMBER := 85;
        v_Grade CHAR(1);
BEGIN
        IF v_Score >= 90 THEN
                v_Grade := 'A';

        ELSIF v_Score >= 80 THEN
                v_Grade := 'B';

        ELSIF v_Score >= 70 THEN
                v_Grade := 'C';

        ELSIF v_Score >= 60 THEN
                v_Grade := 'D';

        ELSE
                v_Grade := 'E';

        END IF;

        DBMS_OUTPUT.PUT_LINE('Grade is ' || v_Grade);
END;
/
**********************************************************************************************************************

 

 

 

 

4. FOR LOOP 문

**********************************************************************************************************************

FOR 루프인덱스 IN [REVERSE] 최저값..최고값 LOOP

      실행할 문장

END LOOP;

**********************************************************************************************************************

- IN REVERSE 를 사용하면 최고값부터 최저값까지 감소하며 수행된다.

 

 

5. 중첩 FOR LOOP 문

**********************************************************************************************************************

FOR 루프인덱스 IN [REVERSE] 최저값..최고값 LOOP

      FOR 루프인덱스 IN [REVERSE] 최저값..최고값 LOOP

            실행할 문장

      END LOOP;

END LOOP;

**********************************************************************************************************************

 

 

[예제2] FOR LOOP 문 사용

**********************************************************************************************************************

set echo on
BEGIN
        FOR v_outerloopcounter IN 1..2 LOOP
                FOR v_innerloopcounter IN 1..4 LOOP
                        DBMS_OUTPUT.PUT_LINE(
                                'Outer Loop counter is ' || v_outerloopcounter ||
                                ', Inner Loop counter is ' || v_innerloopcounter);
                END LOOP;
        END LOOP;
END;
/
**********************************************************************************************************************

 

 

 

6. WHILE LOOP 문

**********************************************************************************************************************

WHILE (조건) LOOP

       (참일 경우 실행)

END LOOP;

**********************************************************************************************************************

- 조건이 거짓이면 WHILE LOOP 문은 한번도 실행되지 않는다.

 

 

[예제3] WHILE LOOP 예

**********************************************************************************************************************

DECLARE

      v_Cnt NUMBER := 0;

BEGIN

       WHILE v_Cnt <= 10 LOOP

              v_Cnt := v_Cnt + 1;

              DBMS_OUTPUT.PUT_LINE('The Value of v_Cnt is ' || v_Cnt);

        END LOOP;

END;

/

**********************************************************************************************************************

 

 

 

7. EXIT 와 EXIT WHEN

 

- Loop를 빠져나갈 때 사용한다. EXIT를 만나면 Loop를 바로 빠져나간다.

- EXIT WHEN (참 조건) : 조건이 참이면 EXIT를 수행한다. WHEN을 사용하면 IF를 사용하지 않아도 된다.

- LOOP를 중간에 멈추도록 하여 속도를 높이기 위해 사용한다.

 

[예제4] EXIT 사용

**********************************************************************************************************************

DECLARE

      v_Cnt NUMBER := 1;

BEGIN

       WHILE TRUE LOOP                                                   (무한루프)

               DBMS_OUTPUT.PUT_LINE('v_Cnt is ' || v_Cnt);

               IF v_Cnd = 10 THEN

                      EXIT;

               END IF;

               v_Cnt := v_Cnt + 1;

        END LOOP;

END;

/

**********************************************************************************************************************

 

 

[예제5] EXIT WHEN 사용  (IF~END IF 대신 EXIT WHEN 사용)

**********************************************************************************************************************

DECLARE

      v_Cnt NUMBER := 1;

BEGIN

       WHILE TRUE LOOP                                                   (무한루프)

               DBMS_OUTPUT.PUT_LINE('v_Cnt is ' || v_Cnt);

               EXIT WHEN v_Cnd = 10;

               v_Cnt := v_Cnt + 1;

        END LOOP;

END;

/

**********************************************************************************************************************

 

 

 

8, 단순 LOOP

- 그냥 Loop 만 사용할 경우 무한 LOOP 가 된다.

- LOOP와 함께 EXIT WHEN을 사용하면 된다.

 

[예제6] LOOP ~ EXIT THEN 사용

**********************************************************************************************************************

DECLARE

      v_Cnt NUMBER := 1;

BEGIN

       LOOP                                                                   (무한루프)

               DBMS_OUTPUT.PUT_LINE('v_Cnt is ' || v_Cnt);

               EXIT WHEN v_Cnd = 10;

               v_Cnt := v_Cnt + 1;

        END LOOP;

END;

/

**********************************************************************************************************************

 

 

[본문스크랩] PL/SQL (6) - 패키지 사용의 예

오라클 | 2007. 12. 21. 15:28
Posted by 시반

###################################################################################################

#   source site : blog.naver.com/tangamjaelt

#   master : 강용운

#   email : tangamjaelt@korea.com

#   last release : 2007.05.18

###################################################################################################

 

회사에서 수많은 오라클 패키지를 볼 수 있다.

내가 짠 건 아니지만, 패키지가 이런 곳에 쓰이는구나라고 처음 알게되었다.

패키지... 언뜻 책만 본 학생들은 감이 오지 않겠지만 실제 필드에서 사용되는 패키지는 강력한 도구임에 틀림없다.

 

DB엔 회사에 관련된 모든 정보가 저장되어 있으며, 이를 관리하는게 DBMS 이다.

DB엔 임직원들의 인사정보가 모두 들어있을 것이며,

인사부에서 사용되는 인사프로그램엔 특정인의 이름을 입력하면 그 사람의 ID가 나온다고 생각해보자.

인사프로그램에서 '사용자ID 조회'라는 메뉴가 있어서 이를 사용하여 '강용운'이란 이름을 쳐 넣으면, 정보가 나올것이다.

 

1. 인사프로그램은 정보를 가져오기 위해 DB에 접속하여 q_account 라는 패키지의 get_userid 프로시저를 호출하게된다.

     패키지 내에는 get_userid 말고도 여러가지 프로시저가 존재하기 때문에 프로시저 이름을 반드시 지정 해주어야 한다.

    인자값으로는 사용자가 입력해준 값 '강용운'이 input 된다.

 

2. 프로시저는 '강용운'이란 값을 받아 DB에서 userid 를 select 하여 찾아낸다.

    결과를 인사프로그램에 Return 해준다.

   

3. 인사프로그램은 받은 결과를 예쁘게(?) 화면에 표시해준다.

 

 

중간에 체크 로직을 넣을 수도 있다.

만약, 이름이 없거나, 한글자만 들어왔다면, 프로시저에서 인자값이 잘못들어 왔음을 인사프로그램에 알리고,

이 코드를 받은 인사프로그램은 사용자에게 다시 확인하라는 메시지를 줄 수 있다.

 

IF v_name IS NULL or length(v_name) < 2 THEN

     error code;

ELSIF

     select userid, username

        from user_account

        where username = v_name;

END IF;

END;

 

[본문스크랩] PL/SQL (4) - 연산자

오라클 | 2007. 12. 21. 15:27
Posted by 시반

###################################################################################################

#   source site : blog.naver.com/tangamjaelt

#   master : 강용운

#   email : tangamjaelt@korea.com

#   last release : 2007.05.07

###################################################################################################

 

연산자 종류

 

- 대입 연산자

      변수   :=    값

 

- 산술 연산자

      ** : 지수연산자. 10**5 = 10*10*10*10*10

      + - * / : 산술계산

 

- 비교 연산자 : 반환값은 True / False.

      =  : 대등 연산자

     <>, !=, ~=  : 부등 연산자

     <, >, <=, >=  : 범위 비교

     LIKE  : 패턴일치 연산자  (log% : log로 시작하는 모든 것.  log___ : log로 시작하고 log 뒤에가 3자리인 것)

     BETWEEN a AND b : 지정한 범위(a~b) 사이

     IN  : 값이 목록내에 있는지 

     IS NULL  : 값이 null인지 조사

 

 

 

[예제1] LIKE 연산자를 사용한 함수  - 함수이기 때문에 RETURN 값을 지정하여야 한다.

********************************************************************************************************************

CREATE OR REPLACE FUNCTION mobile_phone (phone_number IN VARCHAR2)

RETURN VARCHAR2 AS

BEGIN
        IF phone_number LIKE '___-%-____' THEN

                IF SUBSTR(phone_number,1,3) = '011' THEN
                        RETURN 'SK Telecom 011';

                ELSE IF SUBSTR(phone_number,1,3) = '016' THEN
                        RETURN 'KTF 016';

                     ELSE
                        RETURN 'ETC...';

                     END IF;
                END IF;
        END IF;
END;
/
********************************************************************************************************************

 

SQL> set serveroutput on

 

SQL> select * from dba_objects where object_name like 'MOBILE%';  ☞ VALID 상태 확인

 

 

SQL> select mobile_phone('016-0000-0000') MAKER from dual;

 

MAKER
--------------------------------------------------------------------------------
KTF 016

 


 

- 논리 연산자

     AND, OR, NOT

 

- 스트링 연산자

     ||  : 스트링 연결 연산자.  ex) myname = 'Kang' || ' ' || 'Yong Woon';

 

 

 

연산자 우선순위

- 눈으로 확인하기 어려운 복잡한 식의 경우 괄호를 사용하여 우선순위를 제어하거나 보기 쉽게 한다.

 

  ①  **, NOT

  ②  +,- (양수,음수)

  ③  *,/

  ④  +,-,||  

  ⑤  =, <>, !=, ~=, <, >, <=, >=, LIKE, BETWEEN, IN, IS NULL

  ⑥  AND

  ⑦  OR

 

 

NULL

- NULL 값 조사시엔 항상 IS NULL 연산자를 사용해야 한다.    ex) IF a = NULL   ▶   IF a IS NULL

- NVL 함수를 통해 값이 NULL 일때 기본값을 지정할 수 있다.   NVL(식, Null 일때 값)

 

 

형 변환

- 자동으로 형변환이 이루어지거나, 직접 형변환을 지정할 수 있다.

- 자동으로 형변환이 이루어지게 하는 것보다는 명시적으로 변환시키는 것이 좋다.

- 관련 함수

TO_DATE : 문자 → 날짜

TO_NUMBER : 문자 → 숫자

TO_CHAR : 숫자,날짜 → 문자

 

 

[본문스크랩] PL/SQL (3) - 블럭 구조

오라클 | 2007. 12. 21. 15:27
Posted by 시반

###################################################################################################

#   source site : blog.naver.com/tangamjaelt

#   master : 강용운

#   email : tangamjaelt@korea.com

#   last release : 2007.05.04

###################################################################################################

 

PL/SQL을 마스터하기 위해서는 블럭 구조와 블럭의 다양한 종류, 블럭의 사용법을 이해하는 것이 필수적이다.

 

 

Anonymous Block (이름 없는 블럭)

- 아무런 이름이 없는 블럭으로 프로시저나 함수, 트리거의 본문을 형성하지 않는 블럭

- 이는 SQL*Plus 스크립트의 일부로 인라인으로 사용될 수 있으며, 오류 처리 목적으로 프로시저와 함수 블럭 내부에 포함될 수도 있다.

- DECLARE 라는 예약어를 사용하여 시작하고 다음 예약어인 BEGIN 사이에 변수를 선언한다.

- BEGIN 예약어는 블럭의 절차적 부분이 시작된다는 것을 알려준다. 프로그램 코드가 이 부분에 온다.

- EXCEPTION 예약어는 블럭에서 예외 처리 코드를 갖는다.

 

*******************************************************

DECLARE

      변수 선언문;

BEGIN

      프로그램 코드

EXCEPTION

      오류처리 코드

END;

*******************************************************

 

 

Function Block (함수 블럭)

- DECLARE 예약어 대신 그 자리에 함수 헤더가 온다.

- 함수 헤더는 함수 이름과 파라미터들을 기술하고, 반환값의 형을 나타낸다.

- 인수목록 : 함수에 대한 입력 파라미터와 출력 파라미터 목록을 기술한다.

- RETURN : 반환값에 대한 데이터형을 기술한다.

*******************************************************

FUNCTION 이름 [(인수목록)] 

RETURN 데이터형 {IS, AS}

      변수 선언문;

BEGIN

      프로그램 코드

(EXCEPTION

      오류처리 코드)

END;

********************************************************************************************************************

DECLARE
        temp NUMBER;

 

        FUNCTION iifn(boolean_expression IN BOOLEAN,
                        true_number IN NUMBER,
                        false_number IN NUMBER)
        RETURN NUMBER IS

 

        BEGIN
                IF boolean_expression THEN
                        RETURN true_number;


                ELSIF NOT boolean_expression THEN
                        RETURN false_number;


                ELSE
                        RETURN NULL;


                END IF;
        END;

BEGIN
        DBMS_OUTPUT.PUT_LINE(iifn(2>1,1,0));
        DBMS_OUTPUT.PUT_LINE(iifn(2>3,1,0));

        temp := iifn(null, 1, 0);

        IF temp IS NULL THEN
                DBMS_OUTPUT.PUT_LINE('NULL');
        ELSE
                DBMS_OUTPUT.PUT_LINE(temp);
        END IF;
END;
/

********************************************************************************************************************

 

 

 

Procedure Block (프로시저 블럭)

- 함수와 비슷하다.

- 함수와 다른점은 함수는 값을 반환하고 식에 사용할 수 있지만, 프로시저는 값을 반환하지 않으며 식에 활용할 수 없다.

*******************************************************

PROCEDURE 이름 [(인수목록)] {IS, AS}

      변수 선언문;

BEGIN

      프로그램 코드

(EXCEPTION

      오류처리 코드)

END;

********************************************************************************************************************

DECLARE
        first_number NUMBER;
        second_number NUMBER;

 

        PROCEDURE swapn(num_one IN OUT NUMBER,
                        num_two IN OUT NUMBER) IS
                temp_num NUMBER;
        BEGIN
                temp_num := num_one;
                num_one := num_two;
                num_two := temp_num;
        END;

 

BEGIN
        first_number := 10;
        second_number := 20;
        DBMS_OUTPUT.PUT_LINE('First Number =' || TO_CHAR(first_number));
        DBMS_OUTPUT.PUT_LINE('Second Number =' || TO_CHAR(second_number));

 

        DBMS_OUTPUT.PUT_LINE('Swapping...');
        swapn(first_number, second_number);

 

        DBMS_OUTPUT.PUT_LINE('First Number =' || TO_CHAR(first_number));
        DBMS_OUTPUT.PUT_LINE('Second Number =' || TO_CHAR(second_number));
END;
/
********************************************************************************************************************

 중첩 블럭

- Block 내에 Block 이 들어감

- 변수는 블럭 내부에서만 사용 가능하다. 상위 레벨의 변수는 하위 레벨에서 모두 사용 가능하다.

- BEGIN 내에 정의

********************************************************************************************************************

DECLARE
        error_flag BOOLEAN := false;

BEGIN
        DBMS_OUTPUT.PUT_LINE('100~1000 counting');

        DECLARE
                hundreds_counter NUMBER(1,-2);
        BEGIN
                hundreds_counter := 100;

                LOOP
                        DBMS_OUTPUT.PUT_LINE(hundreds_counter);
                        hundreds_counter := hundreds_counter + 100;

                        IF hundreds_counter > 1000 THEN
                                EXIT;
                        END IF;
                END LOOP;
        EXCEPTION
        WHEN OTHERS THEN
                error_flag := true;
        END;

        IF error_flag THEN
                DBMS_OUTPUT.PUT_LINE('Can not count.');
        ELSE
                DBMS_OUTPUT.PUT_LINE('Count Done.');
        END IF;
END;
/
********************************************************************************************************************

 

 

 

 

Trigger Block (트리거 블럭)

- 트리거란 어떤 동작이나 사건이 발생했을 때 샐행되는 코드를 정의하는데 사용된다.

- 처음에 나타나는 구문은 트리거의 종류, 트리거와 연결된 테이블, 트리거가 발생해야 할 때를 말해주는 것이다.

- 예를 들어 특정 User가 CREATE, DROP, ALTER 등의 DDL 문을 실행하게 되면 트리거에서 사용을 막게 할 수 있다.

***************************************************************

CREATE [OR REPLACE] TRIGGER 트리거이름

{BEFORE|AFTER} 동사목록 ON 테이블이름

[[REFERENCING 상호관계이름] FOR EACH ROW [WHEN (조건)]]

DECLARE

      선언문

BEGIN

      PL/SQL코드

END;

****************************************************************

- 동사목록 : 트리거를 발생시키는 SQL 동사

- 테이블이름 : 트리거가 정의되는 테이블

- 조건 : 트리거 실행 조건

- 선언문 : 변수, 레코드, 커서 선언문으로 구성

- PL/SQL코드 : 트리거가 발생할 때 실행되는 PL/SQL 코드

 
블로그 이미지

시반

시반(詩伴)이란 함께 시를 짓는 벗이란 뜻을 가지고 있습니다. 함께 나눌수 있는 그런 공간이길 바라며...

카테고리

분류 전체보기 (233)
개발 이야기 (73)
WEB2.0 (57)
DB2 (24)
MySQL (6)
오라클 (26)
기타 (44)
취미 (0)
잡담 (2)