Static and Dynamic SQL




CS185c

Chris Pollett

Apr 13, 2010

Outline

Introduction

Sample Tables

Department and Employee tables used in example

A Sample SQL Statement

Embedding the Query Statically in C

EXEC SQL DECLARE CS1 CURSOR FOR
Select	empName, deptName, salary+bonus 
From	employee E, department D 
Where E.deptId=D.deptId 
and	salary + bonus > :hv_sum
and	deptName like 'DB2%'; 

EXEC SQL OPEN CS1;
//loop the next line
EXEC SQL FETCH CS1 INTO :hv1, :hv2, :hv3; 

EXEC SQL CLOSE CS1;

Static SQL Application Pre-compile Process

Embedded SQL becoming DSNHLI calls and sections

Quiz

Which of the following statements is true?

  1. In a subselect, the inner select is not allowed to refer to field names used in the outer select.
  2. SQL - Native stored procedures need a C compiler in order to be compiled.
  3. In a DB2 select statement the following two lines are equivalent:
    FROM CHECKOUTS C, MEMBERS M
    
    FROM CHECKOUTS C INNER JOIN MEMBERS M
    

Static SQL Bind Process Flow

What the Parser does

A Parse Tree is Constructed

An example parse tree

Semantic Checking

Query Optimization

An example query plan

Package/Section Generation

Static SQL Execution -- Application Call

A C function and how it calls package sections

Static SQL Execution -- The Loading of Plans and Packages

How DB2 handles a section request

Open Cursor

Fetch and Close

Now let's look at how FETCH and CLOSE get executed.

Deriving a Row of the Result Table

How rows are derived during a fetch request

Dynamic SQL that uses JDBC

How Type2 and Type 4 drivers connect with DB2

Sample JDBC Application

con = DriverManager.getConnection (url);
PreparedStatement pstmt = con.prepareStatement(
"SELECT empName " +
"FROM employee E, department D " +
"WHERE E.deptId = D.deptId " +
"AND salary+bonus > ? " +
"AND deptName like 'DB2%' " );

pstmt.setFloat(1,75000);

rs = pstmt.executeQuery();

while(rs.next()) {
  empName = rs.getString(1);
  System.out.println("EmpName=" + empName) ;
}

rs.close();
pstmt.close();
con.close();