yunsh206

회원가입로그인
http://database.sarang.net/?inc=read&aid=9022&criteria=oracle&subcrit=tutorials&id=9199&limit=20&keyword=&page=12 6.3 EXECUTE IMMEDIATE 의 사용

/* 예제 #10 */
#include
/***************************************************************
This is is a sample Pro*C program which will prompt for a
WHERE clause to be used in an update statement. This is to be
used with EXECUTE IMMEDIATE.
***************************************************************/

EXEC SQL BEGIN DECLARE SECTION;
    VARCHAR uid[20];
    VARCHAR pwd[20];
    char select[132];
EXEC SQL END DECLARE SECTION;
EXEC SQL INCLUDE SQLCA;

void main(void)
{
    char where[80];
    int scode;

    /* log into ORACLE */
    strcpy(uid.arr, "SCOTT");                       /* copy the user name */
    uid.len = strlen(uid.arr);
    strcpy(pwd.arr, "TIGER");                       /* copy the password */
    pwd.len = strlen(pwd.arr);

    EXEC SQL WHENEVER SQLERROR STOP;
    EXEC SQL CONNECT :uid IDENTIFIED BY :pwd;
    printf("Connected to ORACLE user : %sn", uid.arr);

    strcpy(select, "UPDATE EMP SET COMM = 100 WHERE");
    printf("Please enter where clause for the following : n");
    printf("%s", select);
    scode = scanf("%s", where);
    if(scode == EOF !! scode == 0)
    {
        printf("Invalid entry. n");
        exit(1);
    }
    strcat(select, where);

    EXEC SQL EXECUTE IMMEDIATE :select;

    printf("%d records updated. n", sqlca.sqlerrd[2]);
    EXEC SQL WHENEVER SQLERROR CONTINUE;
    EXEC SQL COMMIT WORK RELEASE;
    exit(0);
}

6.4 PREPARE 및 EXECUTE 의 사용



/* 예제 #11 */
#include
/***************************************************************
This is is a sample Pro*C program which will prompt for a
WHERE clause to be used in an update statement. This is to be
used with PREPARE and EXECUTE.
***************************************************************/
EXEC SQL BEGIN DECLARE SECTION;
    VARCHAR uid[20];
    VARCHAR pwd[20];
    float comm;
    char select[132];
EXEC SQL END DECLARE SECTION;
EXEC SQL INCLUDE SQLCA;

void main(void)
{
    char where[80];
    int scode;

    /* log into ORACLE */
    strcpy(uid.arr, "SCOTT");                       /* copy the user name */
    uid.len = strlen(uid.arr);
    strcpy(pwd.arr, "TIGER");                       /* copy the password */
    pwd.len = strlen(pwd.arr);

    EXEC SQL WHENEVER SQLERROR GOTO errrpt;
    EXEC SQL CONNECT :uid IDENTIFIED BY :pwd;
    printf("Connected to ORACLE user : %sn", uid.arr);

    strcpy(select, "UPDATE EMP SET COMM = :comm WHERE");
    printf("Please enter where clause for the follwing : n");
    printf("%s", select);
    scode = scanf("%s", where);
    if(scode == EOF !! scode == 0)
    {
        printf("Invalid entry. n");
        exit(1);
    }
    strcat(select, where);

    EXEC SQL PREPARE S1 FROM :select;

    printf("Please enter commission : ");
    scanf("%f", &comm);
    EXEC SQL EXECUTE S1 USING :comm;

    printf("%d records updated. n", sqlca.sqlerrd[2]);
    EXEC SQL WHENEVER SQLERROR CONTINUE;
    EXEC SQL COMMIT WORK RELEASE;
    exit(0);

errrpt:
    printf("n %70s n", sqlca.sqlerrm.sqlerrmc);
    EXEC SQL ROLLBACK WORK RELEASE;
    exit(1);
}        



6.5 PREPARE, DECLARE, OPEN, FETCH, CLOSE 의 사용



/* 예제 #12 */
#include

/***************************************************************
This is is a sample Pro*C program which will prompt for a
WHERE clause to be used in a select statement.
This sample uses PREPARE, DECLARE, OPEN, FETCH, CLOSE
since this may be a multi-row select and world require a cursor.
***************************************************************/
EXEC SQL BEGIN DECLARE SECTION;
    VARCHAR uid[20];
    VARCHAR pwd[20];
    int deptno;
    float sal;
    char select[132];
EXEC SQL END DECLARE SECTION;
EXEC SQL INCLUDE SQLCA;

void main(void)
{
    char where[80];
    int i, scode;

    /* log into ORACLE */
    strcpy(uid.arr, "SCOTT");                       /* copy the user name */
    uid.len = strlen(uid.arr);
    strcpy(pwd.arr, "TIGER");                       /* copy the password */
    pwd.len = strlen(pwd.arr);

    EXEC SQL WHENEVER SQLERROR GOTO errrpt;
    EXEC SQL CONNECT :uid IDENTIFIED BY :pwd;
    printf("Connected to ORACLE user : %sn", uid.arr);
    strcpy(select, "SELECT ENAME, SAL FROM EMP ");
    printf("Please enter where clause for the following : n");
    printf("%s", select);
    scode = scanf("%s", where);
    if(scode == EOF !! scode == 0)
    {
        printf("Invalid entry. n");
        exit(1);
    }
    strcat(select, where);

    EXEC SQL PREPARE S1 FROM :select;
    EXEC SQL DECLARE C1 CURSOR FOR S1;
    EXEC SQL OPEN C1;
    printf("Employee       tSalary       n");
    printf("--------------t-----------n");

    EXEC SQL WHENEVER NOT FOUND GOTO endloop;
    for(i = 0; ; i++)
    {
        EXEC SQL FETCH C1 INTO :ename, :sal;
      printf("%10st%6.2fn", ename, sal);
    }

endloop:
    printf("nn%d records selected.n", i);
    EXEC SQL WHENEVER SQLERROR CONTINUE;
    EXEC SQL COMMIT WORK RELEASE;
    exit(0);
errrpt:
    printf("n %70s n", sqlca.sqlerrm.sqlerrmc);
    EXEC SQL ROLLBACK WORK RELEASE;
    exit(1);
}


7.1 STORED PROCEDURE 의 사용




/* calldemo.sql */
rem
Rem    calldemo.sql -

Rem    DESCRIPTION
Rem    
Rem    RETURNS
Rem

CREATE OR REPLACE PACKAGE calldemo AS
   TYPE name_array IS TABLE OF emp.ename%type
       INDEX BY BINARY_INTEGER;
   TYPE job_array IS TABLE OF emp.job%type
       INDEX BY BINARY_INTEGER;
   TYPE sal_array IS TABLE OF emp.sal%type
       INDEX BY BINARY_INTEGER;

   PROCEDURE get_employees(
     dept_number IN     number,    -- department to query
     batch_size  IN     INTEGER,   -- rows at a time
     found       IN OUT INTEGER,   -- rows actually returned
     done_fetch  OUT    INTEGER,   -- all done flag
     emp_name    OUT    name_array,
     job         OUT    job_array,
     sal         OUT    sal_array);
END calldemo;
/

CREATE OR REPLACE PACKAGE BODY calldemo AS
   CURSOR get_emp (dept_number IN number) IS
       SELECT ename, job, sal FROM emp
           WHERE deptno = dept_number;

   PROCEDURE get_employees(
     dept_number IN     number,
     batch_size  IN     INTEGER,
     found       IN OUT INTEGER,
     done_fetch  OUT    INTEGER,
     emp_name    OUT    name_array,
     job         OUT    job_array,
     sal         OUT    sal_array) IS

   BEGIN
       IF NOT get_emp%ISOPEN THEN      -- open the cursor if
           OPEN get_emp(dept_number);  -- not already open
       END IF;
       done_fetch := 0;  -- set the done flag FALSE
       found := 0;
       FOR i IN 1..batch_size LOOP
           FETCH get_emp INTO emp_name(i), job(i), sal(i);
           IF get_emp%NOTFOUND THEN    -- if no row was found
               CLOSE get_emp;
               done_fetch := 1;   -- indicate all done
               EXIT;
           ELSE
               found := found + 1;  -- count row
           END IF;
       END LOOP;
   END;
END;
/


/* 예제 #13 */

#include
#include
/***************************************************************
This program connects to ORACLE using the SCOTT/TIGER account.  
The program declares several host arrays, then calls a PL/SQL
stored procedure (GET_EMPLOYEES in the CALLDEMO package)
that fills the table OUT parameters. The PL/SQL procedure returns
up to ASIZE values.
****************************************************************/
EXEC SQL INCLUDE sqlca.h;

typedef char asciz[20];
typedef char vc2_arr[11];

EXEC SQL BEGIN DECLARE SECTION;
    /* User-defined type for null-terminated strings */
    EXEC SQL TYPE asciz IS STRING(20) REFERENCE;
    /* User-defined type for a VARCHAR array element. */
    EXEC SQL TYPE vc2_arr IS VARCHAR2(11) REFERENCE;
    asciz     username;
    asciz     password;
    int       dept_no;                  /* which department to query? */
    vc2_arr   emp_name[10];            /* array of returned names */
    vc2_arr   job[10];
    float     salary[10];
    int       done_flag;
    int       array_size;
    int       num_ret;                 /* number of rows returned */
EXEC SQL END DECLARE SECTION;

long      SQLCODE;

void print_rows();            /* produces program output      */
void sql_error();             /* handles unrecoverable errors */

main()
{
    int   i;
    char  temp_buf[32];

    /* Connect to ORACLE. */
    EXEC SQL WHENEVER SQLERROR DO sql_error();
    strcpy(username, "scott");
    strcpy(password, "tiger");
    EXEC SQL CONNECT :username IDENTIFIED BY :password;
    printf("nConnected to ORACLE as user: %snn", username);

    printf("Enter department number: ");
    gets(temp_buf);
    dept_no = atoi(temp_buf);

    /* Print column headers. */
    printf("nn");
    printf("%-10.10s%-10.10s%sn", "Employee", "Job", "Salary");
    printf("%-10.10s%-10.10s%sn", "--------", "---", "------");

    /* Set the array size. */
    array_size = 10;
    done_flag = 0;
    num_ret = 0;
    /*  Array fetch loop.
     *  The loop continues until the OUT parameter done_flag is set.
     *  Pass in the department number, and the array size--
     *  get names, jobs, and salaries back. */
     for ( ; ; )
    {
        EXEC SQL EXECUTE
            BEGIN calldemo.get_employees
                (:dept_no, :array_size, :num_ret, :done_flag,
                 :emp_name, :job, :salary);
            END;
        END-EXEC;

        print_rows(num_ret);
        if(done_flag) break;
    }
    /* Disconnect from the database. */
    EXEC SQL COMMIT WORK RELEASE;
    exit(0);
}

void print_rows(int n)
{
    int i;

    if (n == 0)
    {
        printf("No rows retrieved.n");
        return;
    }
    for (i = 0; i < n; i++)
        printf("%10.10s%10.10s%6.2fn", emp_name[i ], job[i ], salary[i ]);
}

/* Handle errors. Exit on any error. */
void sql_error()
{
    char msg[512];
    int buf_len, msg_len;

    EXEC SQL WHENEVER SQLERROR CONTINUE;

    buf_len = sizeof(msg);
    sqlglm(msg, &buf_len, &msg_len);

    printf("nORACLE error detected:");
    printf("n%.*s n", msg_len, msg);

    EXEC SQL ROLLBACK WORK RELEASE;
    exit(1);
}


번호 제목 글쓴이 날짜 조회 수 추천 수
835 리눅스 새 하드 장착하기 RanomA 2021.12.01 600 0
834 리눅스 SSH Network error: Software caused connection abort RanomA 2021.05.29 2018 0
833 인터넷 기본 설정 복원 창 띄우는 방법들 file RanomA 2021.05.01 1024 0
832 리눅스 디렉토리별 압축 파일 생성 쉘 스크립트 RanomA 2021.04.04 831 0
831 Javascript 숫자에 끊어 읽기 컴마(,) 추가 RanomA 2020.11.27 752 0
830 Javascript 문자열을 포맷 맞춰 날짜로, 날짜를 포맷 맞춘 문자열로 변환 RanomA 2020.11.26 719 0
829 Javascript 날짜 더하기 RanomA 2020.11.26 451 0
828 Javascript 해당 연월의 마지막 날짜 가져오기 RanomA 2020.11.25 365 0
827 Javascript isNullOrEmpty RanomA 2020.11.25 686 0
826 Javascript 전화번호 포매팅 RanomA 2020.11.25 2309 0
825 Javascript IN RanomA 2020.11.18 261 0
824 Javascript LPAD RanomA 2020.11.17 582 0
823 Adobe Creative Cloud 업데이트 실패 184(혹은 C184) 오류 file RanomA 2020.09.08 1072 0
822 오라클 테이블 레이아웃 조회 Query RanomA 2020.01.13 2064 0
821 SQL Developer의 폰트 설정에서 폰트 목록이 안나타날 때 [6] file RanomA 2019.12.30 4876 0
820 Underscore( _ 문자)를 카멜 케이스(Camel Case)로 변환하기 RanomA 2019.12.06 1815 0
819 라이트룸(Adobe Lightroom) 한자/일본어용 폰트 변경 file RanomA 2018.06.06 2144 0
818 마녀의 빗자루와 악마와의 파티 RanomA 2018.03.23 891 0
817 크레인 안전 점검이 허술해진 게 이명박 때가 아니다? RanomA 2018.01.06 709 0
816 인도 중국의 분쟁 지역 file RanomA 2017.08.17 1295 0