1 Embedding SQL in High Level Language Programs

advertisement
Embedding SQL in High
Level Language Programs
Alison Butterill
IBM i Product Manager
Power Systems
Agenda
yIntroduction
yBasic SQL within a HLL program
yProcessing multiple records
yError detection
yDynamic SQL
yTips and Techniques
ySummary
2
© 2012 IBM Corporation
1
What is SQL?
SQL - Structured Query Language
yData language for manipulation of a Relational database
yEnglish keyword-oriented
yExcellent tool for application development environment
ƒQuery
ƒData definition
ƒData manipulation
ƒData control
yPowerful language for Set-At-A-Time processing
SQL is NOT an end user query product!
3
© 2012 IBM Corporation
Executing SQL on IBM i
yInteractive SQL
yEmbedded or compiled in application programs
yQuery Manager
ySQL Statement Processor
yOperations Navigator
yDynamic SQL
ySQL Procedure Language
yExtended Dynamic SQL
yODBC, JDBC
yJSQL or SQLJ
yX/Open SQL Call Level Interface
4
© 2012 IBM Corporation
2
V5 SQL Support...
Part 1: DB2 Database Manager
yIncluded with IBM i (operating system)
ƒV5: 5722-SS1
ySQL parser and run time support
ƒSQL license (5722-ST1) not required to run SQL
applications
ƒSupport for compiled programs using embedded SQL
ySQL APIs
ƒQSQPRCED - Provides extended dynamic SQL capability
ƒQSQCHKS - Provides syntax checking for SQL
statements
yX/Open SQL Call Level Interface
yV5R1 - SQL Statement Processor
ƒRUNSQLSTM Command
5
© 2012 IBM Corporation
V5 SQL Support
Part 2: DB2 for IBM i Query Manager & SQL Development Kit
yProgram number 5722-ST1
yQuery Manager
yInteractive SQL
ySQL precompilers
ƒRequired for embedding SQL in HLL programs
ƒMore later
ySQL REXX interface
6
© 2012 IBM Corporation
3
Agenda
yIntroduction
yBasic SQL within a HLL program
yProcessing multiple records
yError detection
yDynamic SQL
yTips and Techniques
ySummary
7
© 2012 IBM Corporation
High Level Languages Supported
yRPG
yCOBOL
yC
yJava
yAS/400 PL/I
yFORTRAN/400
8
© 2012 IBM Corporation
4
The SQL Precompiler
SQL
Precompiler
User
Source
File
Syntax check
X-ref host variables
SQL statements to calls
Comment SQL statements
Language
Compiler
Modified
Source
File
Processed
SQL
Statements
9
Program
Access
Plan
© 2012 IBM Corporation
SQL Commands
Basic commands
ySELECT - retrieves data; one row or multiple
yUPDATE - updates one row or multiple
yDELETE - deletes one row or multiple
yINSERT - adds one row or multiple
Additional functions for complex processing
yDECLARE CURSOR – builds temp result table
yOPEN and CLOSE – open/close result table
yFETCH – row retrieval
yCOMMIT and ROLLBACK – journaling functions
yGRANT and REVOKE – security functions
10
© 2012 IBM Corporation
5
Basic RPG Interface
I
DS
I
I
I
C*
C/EXEC SQL
C+
SELECT
C+
INTO
C+
FROM
C+
WHERE
C/END-EXEC
1
6
31
50 EMPNBR
30 NAM
32 DEPT
nbr, nam, dpt
:empnbr, :nam, :dept
emp
nbr = :empnbr
•Retrieve column/field values into program variables
•One-to-one correspondence between SELECT list and INTO
list
•SELECT … INTO expects only a single row/record
–Multiple rows require the use of cursor operations
11
© 2012 IBM Corporation
Basic Cobol Interface
WORKING-STORAGE SECTION.
77 EMPNBR
PIC S9(5) COMP-3.
77 DEPT
PIC S9(3) COMP-3.
77 NAM
PIC
X(25).
.
PROCEDURE DIVISION.
EXEC SQL
SELECT nbr, nam, dpt
INTO :empnbr, :nam, :dept
FROM emp
WHERE nbr = :empnbr
END-EXEC.
•Retrieve column/field values into program variables
•One-to-one correspondence between SELECT list and INTO
list
•SELECT … INTO expects only a single row/record
–Multiple rows require the use of cursor operations
12
© 2012 IBM Corporation
6
Prompting for SQL
yUse SQL source member types
–e.g., SQLRPG, SQLRPGLE, SQLCBL, SQLCBLLE
–Prompting will not work without SQL member type
ySEU supports prompting today; RSE does not today
yBoth EXEC SQL and END-EXEC statements must be in place
–Then prompting (F4) will work for statements in between
–Same prompter as interactive SQL (Start ISQL command)
yCompile commands
–OPM compilers
ƒCRTSQLRPG, CRTSQLCBL
–ILE compilers
ƒCRTSQLRPGI, CRTSQLCBLI
ƒCreates either *PGM, *SRVPGM or *MODULE depending on
parameter value specified for "Compile type" or OBJTYPE
13
© 2012 IBM Corporation
Prompting Embedded SQL
Columns . . . :
1 71
Edit
SKIP/QRPGSRC
SEU==> _____________________________________________
AASQLTST
FMT ** ...+... 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+.
*************** Beginning of data **********************
0011.00
C/EXEC SQL
0012.00 ==>> C+
<<=== Prompt from
0013.00 ==>> C+
SELECT
<<===
any of
0014.00 ==>> C+
<<=== these lines
0015.00
C/END-EXEC
****************** End of data *************************
F3=Exit
F4=Prompt
F16=Repeat find
F5=Refresh
F9=Retrieve
F17=Repeat change
F10=Cursor
F24=More keys
Any SQL statement can be prompted from within a source program
14
© 2012 IBM Corporation
7
Prompting for Embedded SQL
Specify SELECT Statement
Type information for SELECT statement.
FROM files . . . . .
SELECT fields . . .
WHERE conditions . .
GROUP BY fields . .
HAVING conditions .
ORDER BY fields . .
FOR UPDATE OF fields
.
.
.
.
.
.
.
.
.
.
.
.
.
.
Press F4 for a list.
emp_______________________________
nbr,_nam,_sal_____________________
dpt_=_:dept_______________________
__________________________________
__________________________________
__________________________________
sal_______________________________
Bottom
Type choices, press Enter.
Number of records to optimize .
DISTINCT records in result file
FOR FETCH ONLY . . . . . . . . .
UNION with another SELECT . . .
F3=Exit
F10=Copy
F4=Prompt
F12=Cancel
F5=Refresh
F14=Delete
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
__________
N
Y=Yes, N=No
N
Y=Yes, N=No
N
Y=Yes, N=No
F6=Insert line
F15=Split line
15
F9=Subquery
F24=More keys
© 2012 IBM Corporation
Prompting for Embedded SQL…
Results of Prompting:
Columns . . . :
1 71
Edit
SKIP/QRPGSRC
SEU==> _____________________________________________
AASQLTST
FMT ** ...+... 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+.
*************** Beginning of data **********************
0011.00
C/EXEC SQL
0012.00
C+
0013.00
C+
SELECT nbr, nam, sal
0013.01
C+
FROM emp
0013.02
C+
WHERE dpt = :dept
0013.03
C+
FOR UPDATE OF sal
0014.00
C+
0015.00
C/END-EXEC
****************** End of data *************************
F3=Exit
F4=Prompt
F16=Repeat find
16
F5=Refresh
F9=Retrieve
F17=Repeat change
F10=Cursor
F24=More keys
© 2012 IBM Corporation
8
Embedded SQL in Free Format RPG
SQL Statement
Start of SQL statement
17
© 2012 IBM Corporation
Using Structures in SQL
yHost structures are groups of variables
–Data structures in RPG
–Group items in COBOL
yStructures can be used in SQL statements
yReplaces list of variables
18
© 2012 IBM Corporation
9
Using HLL Structures with SQL
RPG
COBOL
I
empds
DS
I
I
I
C*
C/EXEC SQL
C+
SELECT nbr, nam, dpt
C+
INTO :empds
C+
FROM emp
C+
WHERE nbr = :empnbr
C/END-EXEC
1
6
31
50 EMPNBR
30 NAM
31 DEPT
WORKING STORAGE SECTION.
01 EMP_DATA.
05 NBR PIC S9(5) COMP-3.
05 DEPT PIC S9(1) COMP-3.
05 NAME PIC X(25).
PROCEDURE DIVISION
MOVE 5 TO NBR.
EXEC SQL
SELECT nbr, pos, nam
INTO :EMP_DATA
FROM empl WHERE pos=:DEPT
END-EXEC.
19
© 2012 IBM Corporation
Agenda
yIntroduction
yBasic SQL within a HLL program
yProcessing multiple records
yError detection
yDynamic SQL
yTips and Techniques
ySummary
20
© 2012 IBM Corporation
10
Selecting and Processing Multiple Rows
Steps to access multiple rows:
1 Declare SQL cursor
2 Open cursor
3 Fetch next record
4 Process record (UPDATE/INSERT/etc)
5 If last record: go to Step 6,
else: go to Step 3
6 Close cursor
21
© 2012 IBM Corporation
Selecting and Processing Multiple Rows …
DECLARE CURSOR Statement
•Similar in function to HLL file declarations
–F-specs or FD's
–No processing actually takes place - just definition
•Host variables may be included in the statement
•Created using an embedded SELECT command
–most SELECT clauses may be used - ORDER BY, GROUP BY, etc
•Coded in C-specs of RPG or Procedure Division of COBOL
•Must be declared before being referenced
C*
C/EXEC SQL
C+
C+
DECLARE empcsr CURSOR FOR
C+
SELECT nbr, nam, sal
C+
FROM emp
C+
WHERE dpt = :dept
C+
C/END-EXEC
C*
22
© 2012 IBM Corporation
11
Selecting and Processing Multiple Rows …
DECLARE CURSOR Statement – additional clauses
C*
C/EXEC SQL
C+
C+
DECLARE empcsr CURSOR FOR
C+
SELECT nbr, nam, sal
C+
FROM emp
C+
WHERE dpt = :dept
C+
FOR UPDATE OF sal
C+
C/END-EXEC
C*
yBy default, all columns may be updated or deleted
–FOR UPDATE OF - lists the columns that are to be updated
ƒonly columns NOT included in ORDER BY are eligible
–FOR READ ONLY - specifies no updating/deleting allowed
yConsiderations:
–FOR READ ONLY - may improve performance; better
documentation
–FOR UPDATE OF - security; may improve performance
–FOR READ ONLY with “insensitive” clause
23
© 2012 IBM Corporation
Selecting and Processing Multiple Rows …
DECLARE CURSOR Statement – additional clauses
C*
C/EXEC SQL
C+
C+
DECLARE empcsr CURSOR FOR
C+
WITH HOLD
C+
SELECT nbr, nam, sal
C+
FROM emp
C+
WHERE dpt = :dept
C+
FOR UPDATE OF sal
C+
C/END-EXEC
C*
yWith Hold clause useful with commitment control
yDefault – cursors are closed with commit/rollback commands
yWith Hold – keeps cursor open
yWith Hold also an optional clause on the commit/rollback statements
24
© 2012 IBM Corporation
12
OPEN Statement
•Executes the SELECT Statement For a Declared
Cursor
•Builds the access path if necessary
•Successful Open places the file cursor before the first
row of the result table
•Cursor must be closed before it can be opened
C*
C/EXEC SQL
C+
C+
OPEN
C+
C/END-EXEC
C*
empcsr
25
© 2012 IBM Corporation
FETCH Statement
Two Functions
yPosition the cursor for the next operation
C*
C/EXEC SQL
C+
C+
FETCH
C+
C/END-EXEC
NEXT
FROM
empcsr
yBring rows/records into the program
C*
C/EXEC SQL
C+
C+
FETCH NEXT FROM empcsr
C+
INTO :number, :name, :salary
C+
C/END-EXEC
26
© 2012 IBM Corporation
13
Selecting and Processing Multiple Rows …
FETCH Statement
yAlternatives to Next processing
yCursor must be defined as a scrollable
Keyword
Next
Prior
First
Last
Before
After
Current
Positions Cursor
On the next row after the current row
On the row before the current row
On the first row
On the last row
Before the first row - must not use INTO
After the last row - must not use INTO
On the current row (no change in position)
Relative n
n < -1 Positions to nth row before current
n = -1 Same as Prior keyword
n = 0 Same as Current keyword
n = 1 Same as Next keyword
n > 1 Positions to nth row after current
27
© 2012 IBM Corporation
Selecting and Processing Multiple Rows …
FETCH Statement
yAlternatives to Next Processing
yCursor must be defined as a scrollable
C/EXEC SQL
C+
C+
DECLARE empcsr SCROLL CURSOR FOR
C+
SELECT nbr, nam, sal
C+
FROM emp
C+
ORDER BY empid
C+
C/END-EXEC
C*
C/EXEC SQL
C+
C+
FETCH PRIOR FROM empcsr
C+
INTO :number, :name, :salary
C+
C/END-EXEC
28
© 2012 IBM Corporation
14
Selecting and Processing Multiple Rows …
Positioned Update and Delete Statements
yUpdates or deletes the current row of an updatable cursor
yCan only be done after successful Fetch operation
y"Where Current of" clause in Update and Delete statements
C/EXEC SQL
C+
DECLARE empcsr CURSOR FOR
C+
SELECT nbr, nam, sal
C+
FROM emp
C+
ORDER BY empid
C+
FOR UPDATE OF sal
C/END-EXEC
C*
C/EXEC SQL
C+
FETCH NEXT FROM empcsr
C+
INTO :number, :name, :salary
C/END-EXEC
C*
C/EXEC SQL
C+
UPDATE emp
C+
SET sal = sal + :raise
C+
WHERE CURRENT OF empcsr
C/END-EXEC
29
© 2012 IBM Corporation
Selecting and Processing Multiple Rows:
CLOSE Statement
•Closes the cursor
•Cursor must be opened in order to be closed
•DB2 for i5/OS closes cursors for other reasons also:
–job end
–activation group ends
–program ends
–modules ends
–commit or rollback without a 'with hold' clause
–error handling......
•Rule of thumb - close the cursor when finished with it
C*
C/EXEC SQL
C+
C+
CLOSE
C+
C/END-EXEC
30
empcsr
© 2012 IBM Corporation
15
Selecting and Processing Multiple Rows …
Example: Update SALARY for all records in a specified department
C*
C/EXEC SQL
C+
C+
DECLARE empcsr CURSOR FOR
Define
C+
SELECT nbr, nam, sal
C+
FROM emp
C+
WHERE dpt = :dept
C+
FOR UPDATE OF sal
C+
C/END-EXEC
C*
C
EXFMT PROMPT
C*
C/EXEC SQL
Load
C+
NOTE: Not all
C+
OPEN empcsr
program logic is
C+
shown!!
C/END-EXEC
31
© 2012 IBM Corporation
Selecting and Processing Multiple Rows …
Example Continued
C*
C/EXEC SQL
C+
C+
FETCH NEXT FROM empcsr
Retrieve
C+
INTO :number, :name, :salary
C+
C/END-EXEC
C*
C/EXEC SQL
C+
C+
UPDATE emp
Process
C+
SET sal = sal + :raise
C+
WHERE CURRENT OF empcsr
C+
C/END-EXEC
C*
C/EXEC SQL
NOTE: Not all
Close
C+
program logic is
C+
CLOSE empcsr
shown!!
C+
C/END-EXEC
32
© 2012 IBM Corporation
16
Agenda
yIntroduction
yBasic SQL within a HLL program
yProcessing multiple records
yError detection
yDynamic SQL
yTips and Techniques
ySummary
33
© 2012 IBM Corporation
Error Detection and Handling
•Status always returned to HLL code
–both successful and unsuccessful statements
•Programmer must check return codes within program
•SQL Communications Area (SQLCA)
–contains feedback information
–must be included in all SQL programs
–RPG includes SQLCA automatically
–other languages must have specific include:
EXEC
SQL
INCLUDE SQLCA
END-EXEC
34
© 2012 IBM Corporation
17
Error Detection and Handling
SQL Communications Area (SQLCA)
SQLCAID
SQLCABC
SQLCode
SQLErrML
SQLErrMC
SQLErrP
SQLErrD
Char(8)
Integer
Integer
SmallInt
Char(70)
Char(8)
Array of Integers
Structure identifying literal: "SQLCA"
Length of SQLCA
Return code
Length of SQLErrMC
Message Replacement text
Product ID literal: "QSQ" for DB2/400
SQLErrD(1) - treated as Char(4); last 4 characters
of CPF or other escape message
SQLErrD(2) - treated as Char(4); last 4 characters
of CPF or other diagnostic message
SQLErrD(3) - for Fetch, Insert, Update or Delete,
number of rows retrieved or updated
SQLErrD(4) - for Prepare, relative number
indicating resources required for
execution
SQLErrD(5) - for multiple-row Fetch, contains 100
if last available row is fetched;
for Delete, number of rows affected
by referential constraints; for
Connect or Set Connection,
contains t-1 if unconnected, 0 if local
and 1 if connection is remote
SQLErrD(6) - when SQLCode is 0, contains
SQL completion message id
35
© 2012 IBM Corporation
Error Detection and Handling
SQL Communications Area (SQLCA) - continued
36
SQLWarn
SQLWarn0
Char(11)
Char(1)
SQLWarn1
Char(1)
Set of 11 warning indicators; each is blank, W, or N
Blank if all other SQLWARNx warning indicators are blank
W if any warning indicator contains W or N
W if a string column was truncated when assigned to host variable
SQLWarn2
SQLWarn3
Char(1)
Char(1)
W if null values were eliminated from a function
W if number of columns is larger than number of host variables
SQLWarn4
Char(1)
SQLWarn5
SQLWarn6
SQLWarn7
SQLWarn8
Char(1)
Char(1)
Char(1)
Char(1)
SQLWarn9
SQLWarnA
SQLState
Char(1)
Char(1)
Char(5)
W if prepared Update or Delete statement doesn't include a Where
clause
Reserved
W if date arithmetic results in end-of-month adjustment
Reserved
W if result of character conversion contains the substitution
character
Reserved
Reserved
Return code; "00000' if no error or warning
© 2012 IBM Corporation
18
Error Detection and Handling
SQLCODE Values
•SQLCODE (SQLCOD) contains return code
• = 0 Successful statement execution
• > 0 Successful, with warning condition
• < 0 Unsuccessful - statement failed
•SQLCODE value indicates exact error or condition
•e.g. 100 = Row not found (or end of file)
•e.g. -552 = Not authorized to object
•SQLCODE values have corresponding messages
•e.g. SQL0100 = Row not found
•e.g. SQL0552 = Not authorized to &1.
37
© 2012 IBM Corporation
Error Detection and Handling
RPG
COBOL
38
C/EXEC SQL
C+ SELECT name INTO :nam
C+
WHERE emp = 100
C/END-EXEC
C
SQLCOD
IFLT
C
C
C
SQLCOD
IFGT
C
C
0
EXSR
ENDIF
0
EXSR
ENDIF
ERR
NF
EXEC SQL
SELECT name INTO :lastname
WHERE emp = 100
END-EXEC.
IF SQLCODE < 0
PERFORM ERROR-ROUTINE.
ELSE
IF SQLCODE > 0
PERFORM NOT-FOUND-ROUTINE
ELSE
PERFORM GOOD-REC-ROUTINE.
© 2012 IBM Corporation
19
Error Handling and Detection
WHENEVER Statement
•WHENEVER statement checks SQLCA
•Can branch to a location based on condition
•Three conditions:
–SQLWARNING (SQLCODE > 0 except 100)
ƒ OR (SQLWARN0 = 'W')
–SQLERROR (SQLCODE < 0)
–NOT FOUND (SQLCODE = 100)
•Two possible actions
–CONTINUE
–GO TO label
C*
C/EXEC SQL
C+
C+
WHENEVER SQLERROR GO TO error
C+
C/END-EXEC
39
© 2012 IBM Corporation
Error Detection and Handling – Better Way
•Directly following each SQL statement - code an 'error catcher'
•Easier to determine source of the error
•More discrete method of determining action to be taken
Example: Update SALARY for all records in a specified department
C*
C/EXEC SQL
C+
C+
DECLARE empcsr CURSOR FOR
Define C+
SELECT nbr, nam, sal
C+
FROM emp
C+
WHERE dpt = :dept
C+
FOR UPDATE OF sal
NOTE: Not all
C+
program logic is
C/END-EXEC
shown!!
C*
C
EXFMT PROMPT
C* Read operation of EXFMT retrieve dept number
40
© 2012 IBM Corporation
20
Selecting and Processing Multiple Rows …
Example Continued
Load
Retrieve
C*
C/EXEC SQL
C+
OPEN empcsr
C/END-EXEC
C*
C
IF SQLCODE <> 0
C
EXSR Err
C
DOU = 100
C*
C/EXEC SQL
C+
FETCH NEXT FROM empcsr
C+
INTO :number, :name, :salary
C/END-EXEC
C*
C
IF SQLCODE <> 0
NOTE: Not all
C
EXSR Err
program logic is
C
DOU = 100
C*
shown!!
41
© 2012 IBM Corporation
Selecting and Processing Multiple Rows …
Example Continued
Process
Close
C*
C/EXEC SQL
C+
UPDATE emp
C+
SET sal = sal + :raise
C+
WHERE CURRENT OF empcsr
C/END-EXEC
C*
C
IF SQLCODE <> 0
C
EXSR Err
C
ENDIF
C
ENDIF
C
ENDDO
C*
C/EXEC SQL
C+
CLOSE empcsr
NOTE: Not all
C/END-EXEC
program logic is
shown!!
42
© 2012 IBM Corporation
21
Agenda
yIntroduction
yBasic SQL within a HLL program
yProcessing multiple records
yError detection
yDynamic SQL
yTips and Techniques
ySummary
43
© 2012 IBM Corporation
Dynamic SQL
What is Dynamic SQL?
•Dynamic SQL is a different way to use SQL
•SQL statements are not pre-defined in program
–Dynamically created on the fly as part of
program logic
•SQL pre-compiler cannot fully process dynamically
created SQL statements
•PREPARE statement used in program logic to
compile dynamically created SQL statements
–Can be used with SQL EXECUTE statement
44
© 2012 IBM Corporation
22
Dynamic SQL
What is Dynamic SQL?
•Offers a high degree of application flexibility
•Can create/build SQL statement
•Based on parameters received from
•Interactive user interface
•List selection techniques
•Application control file
•Use any programming language
45
© 2012 IBM Corporation
Dynamic SQL
Where to use Dynamic SQL
yReport programs with user run time selection
–Files
–Fields
–Record selection criteria
–Sorting
–SQL built in functions
yWhenever the exact syntax of an SQL statement cannot
be determined beforehand
46
© 2012 IBM Corporation
23
Dynamic SQL – Example 1
User prompted to enter the delete condition (InpCond variable)
C*
C
Eval
SQLStmtStr = 'Delete From Customer
C
Where '
C
Eval
SQLStmt = SQLStmtStr + InpCond
C/EXEC SQL
C+
C+
PREPARE DynSQLStmt
C+
FROM :SQLStmt
C+
C/END-EXEC
C*
C
If
(SQLCod = 0) And (SQLWn0 = *Blank)
C/EXEC SQL
C+
C+
EXECUTE DynSQLStmt
C+
C/END-EXEC
C*
47
© 2012 IBM Corporation
Dynamic SQL
Example 2: Dynamically select records from the Employee
Master File - Any fields, records, or sequence
C* User prompted to enter delete condition (InpCnd)
C*
C/EXEC SQL
C+
C+
PREPARE search FROM :sqlstm
C+
C/END-EXEC
C*
C/EXEC SQL
C+
C+
DECLARE empcsr CURSOR FOR search
C+
C/END-EXEC
C*
C/EXEC SQL
C+
C+
OPEN empcsr
C+
C/END-EXEC
48
© 2012 IBM Corporation
24
Dynamic SQL
Performance considerations
yDynamic SQL can be resource intensive
yRemember that a dynamic SQL statement is parsed
(interpreted) and executed within the application program
from which it is called
–
May have negative impact on performance
Use it ... But use it carefully!
49
© 2012 IBM Corporation
Agenda
yIntroduction
yBasic SQL within a HLL program
yProcessing multiple records
yError detection
yDynamic SQL
yTips and Techniques
ySummary
50
© 2012 IBM Corporation
25
Performance Tips
Embedded SQL Tips
•Test statements in Interactive SQL before embedding them
–When exiting Interactive SQL session
ƒYou can save session statements to a source member
ƒThen copy from this member into your program source
•Default for SQL is to use Commitment Control
–Requires journaling
ƒProgram execution fails if updated files are not journaled
–To request no commitment control
ƒCOMMIT(*NONE) on compile
•SQL precompile step happens before RPG/COBOL compile
–Therefore, if SQL syntax or semantic error occurs, no "typical"
compile source listing available
–Can be very difficult to work through problems at this stage
51
© 2012 IBM Corporation
Performance Tips
Designing and Writing Efficient SQL Queries
•SQL uses two basic ways to retrieve data
–Dataspace scan or arrival sequence Generally used
when MORE than 20% of records will be selected
–Index based or keyed access Generally used when
LESS than 20% of records will be selected
•If SQL can use an index, performance can improve
significantly!
•Create indexes for columns frequently referenced in
–WHERE clause
–GROUP BY clause
–ORDER BY clause
•Create indexes for fields that are frequently used to join
files
52
© 2012 IBM Corporation
26
Performance Tips
Performance Analysis Tools
•PRTSQLINF
–Prints information about the embedded SQL
statements in a program, SQL package or service
program
ƒSQL statements
ƒAccess plans
ƒList of command parameters used by precompiler
•STRDBMON
•Predictive Query Governor
–CHGQRYA command
•TRCJOB
•Visual Explain (first in V4R5)
–Operations Navigator
53
© 2012 IBM Corporation
Performance Tips
Multiple Row FETCH
•Based on host structure
–RPG - Multiple Occurence Data Structure
–COBOL - Occurs clause on declaration of the group item
•Clause on FETCH
•FOR n ROWS (n = number of rows to be returned)
•Specifies number of rows to be retrieved to fill the structure
D
EMP
DS
D
NBR
D
NAME
D
JOB
C*
C
Z-ADD
C/EXEC SQL
C+
FETCH Next
C+
FROM CustomerCursor
C+
FOR 10 ROWS
C+
INTO Emp
C/END-EXEC
C
Eval
C*
54
5
25
1
5
Occurs(10)
0
JOB
ErrCond = SQLErrD(5)
© 2012 IBM Corporation
27
Performance Tips
Multiple Row FETCH - continued
yFirst row fetched- placed into first element of host structure
yFetching stops when n rows are returned - or no more records
yProgram variable may be used to specify number of records to
be fetched (Note: RPG IV - %Elem built in function)
yBe Careful - Fetching is always forward from position set by
positioning keyword
–FETCH RELATIVE -3 .... FOR 3 ROWS
–is not the same as
–FETCH PRIOR .... FOR 3 ROWS
yResults:
–SQLCA updates SQLErrCode(3) to reflect # rows retrieved
–If no rows returned and no other exceptions, SQLCode is
100
–If row(s) returned contains last available row,
SQLErrCode(5) set to 100
55
© 2012 IBM Corporation
Performance Tips
Blocked INSERT
•Multiple elements from a host structure are inserted
into a table
•Program variable may be used to set the number of
records to be inserted
•Executes as if n INSERT statements had been issued
–but with improved performance
D
EMP
DS
D
NBR
5
D
NAME
25
D
JOB
C*
C/ EXEC SQL
C+
INSERT INTO Customer
C+
10 ROWS
C+
VALUES :Emp
C/ END-EXEC
56
Occurs(10)
0
1
© 2012 IBM Corporation
28
Other Uses for Embedded SQL
•Remote Database Access
–CONNECT TO
–DISCONNECT
–RELEASE ALL
–SET CONNECTION
•Stored Procedures
–DECLARE PROCEDURE
–CALL PROCEDURE
•INCLUDE statement
•Dynamic Cursor
•Query Manager
57
© 2012 IBM Corporation
Agenda
yIntroduction
yBasic SQL within a HLL program
yProcessing multiple records
yError detection
yDynamic SQL
yTips and Techniques
ySummary
58
© 2012 IBM Corporation
29
Summary
•Practical, effective solution for applications
requiring complex data retrieval
•Very flexible, functional tool for development
–Embedded in a HLL program
–Entered interactively
•Portability to other relational databases
–Easy report writing with programmable
flexibility
•Similarity across many relational databases
59
© 2012 IBM Corporation
Bibliography
•DB2 cross platform web page – includes a pointer to a free DB2
Programming FastPath course download
•SQL/400 Developer’s Guide - Paul Conte and Mike Cravitz
•Database Design and Programming for DB2/400 - Paul Conte
•S246-0100 DB2/400: The New AS/400 Database: V3R1 - Skip
Marchesani
•Informational APARs (II09006)
•IBM Publications on the Web
•Books
•http://www1.ibm.com/servers/eserver/systemi/db2/books.htm
•White Papers
http://www1.ibm.com/servers/eserver/systemi/db2/db2awp_m.htm
•Information Centre
http://www.systemi.ibm.com/infocentre
GO -> Database and file systems -> DB2 for i5/OS
60
© 2012 IBM Corporation
30
Thank You
31
Download