<Dynamic SQL - Method>

그전에 먼저.. remind

Dynamic SQL
: dynamic SQL이란 string형 변수에 담아서 기술하는 Sql문장.
변수를 사용하므로 조건에따라 sql문을 동적으로 바꿀 수 있고,
런타임 시 사용자로부터 sql문의 일부 또는 전부를 입력받아서 실핼 수도 있음
-> precompile 시 syntax, semantics체크가 불가능

Static SQL
: string형 변수값을 담지 않고, 코드 사이에 직접 기술한 sql문장.
= Embedded SQL이라고도 함. -> 우리는 gpec이라 부름??
-> 변수에 담지않고 마치 예약된 키워드처럼 코드 사이에 섞어서 쓰임
-> dynamic이나 static이나 precompile 단계를 거치면 변수에 담기는건 마찬가지지만,!
static은 런타임 시 절대 변하지 않음
-> precomfile 단계에서 구문 분석, 유효 객체여부, 액세스 권한 등을 체크할 수 있음



■ Method 1
1. EXECUTE IMMEDIATE로 즉시 실행
2. SELECT 문같은 query 문이 아니어야함.( INSERT, DELETE, CREATE 등만 가능)
3. 호스트 변수는 없음(입력 출력 다없음)
[따라서 가능한 쿼리는 아래 같은 쿼리 변수도 없고 SELECT 문도 아닌 SQL]

(ex)
'DELETE FROM EMP WHERE DEPTNO = 20'
'GRANT SELECT ON EMP TO scott'


■ Method 2
1. PREPARE 하고 EXECUTE로 실행
2. SELECT문 즉, query문이 아니고 입력되는 호스트변수의 갯수가 정해져 있는경우

(ex)
'INSERT INTO EMP (ENAME, JOB) VALUES (:emp_name, :job_title)'
'DELETE FROM EMP WHERE EMPNO = :emp_number'


■ Method 3
1. PREPARE과  DECLARE, OPEN, FETCH, CLOSE문 같이 사용할 수 있음.
2. SELECT문에서 사용(query)
3. 입력호스트 변수와, 출력호스트 변수가 정해져 있어야함.

(ex)
'INSERT INTO EMP (ENAME, JOB) VALUES (:emp_name, :job_title)'
'DELETE FROM EMP WHERE EMPNO = :emp_number'


■ Method 4
1. SELECT, INSERT, UPDATE 등 다 가능함.
2. 입력이 몇개인지 출력이 몇개인지 정해지지 않음.(입력 받게됨)
3. JDBC에서의 SQL 사용법과 비슷하다고 보면됨.
4. 코딩하기가 어려움.

(ex)
'INSERT INTO EMP (<unknown>) VALUES (<unknown>)'
'SELECT <unknown> FROM EMP WHERE DEPTNO = 20'




* Avoiding common errors
If you use a character array to store the dynamic SQL statement, blank-pad the array before storing
the SQL statement. That way, you clear extraneous characters. This is especially important when you reuse
the array for different SQL statements. As arule, always initialize (or reinitialize) the host string before storing the SQL statement.
Do not null-terminate the host sting. Oracle does not recognize the null terminator as an end-of-string sentinel.
Inestead, Oracle treats it as part of the SQL statement.
If you use a VARCHAR variable to store the dynamic SQL statement, make sure the length of the VARCHAR
is set (or reset) correctly before you execute the PREPARE or EXECUTE IMMEDIATE statement.
EXECUTE resets the SQLWARN warning flags in the SQLCA. So, to catch mistakes such as an unconditional update
(caused by omitting a WHERE clause), check the SQLWARN flags after executing the PREPARE statement
but before executing the EXECUTE statement.



+ Recent posts