IBM Insight 2014
3
Introduction to SQL Procedures
• What is an SQL Stored Procedure?
• A stored procedure that contains only SQL statements
• May use SQL control statements to write the logic part of the
program (e.g. WHILE, IF, GOTO, REPEAT, etc.)
• SQL Procedural Language or SQL PL
• Two types of SQL Stored Procedures
• External SQL Procedures (from V5 on) - Generated C program
which runs in a WLM environment
• Native SQL Procedures (from DB2 9 on) - The SQL procedure
logic runs in the DBM1 address space
4
When to Use Native SQL Procedures
• Go To Option When ….
• SQL intensive
• Contains minimal application logic
• Lowest billable cost (for remote) and productivity are the most
important priorities i.e. the stored procedure execution itself is
zIIP offloadable
• Classic Example is TPC-C:
• An OLTP application for order-entry consisting of entering and
delivering orders, recording payments, checking the status of orders,
and monitoring the level of stock at the warehouses
• Consider Alternatives When ….
• Contains significant amount of application logic
• Many IF/WHILE/CASE/REPEAT statements
• Executes math, string, file manipulation functions
IBM Insight 2014
5
Benefits of Using Templates
• They engrain good programming practices
• You can leverage existing programming standards
• Begin all parameters with their own same naming convention e.g. P_
or IN_ or P_IN_
• Begin all variables with their own same naming convention e.g. V_ or
x
• Initialize all variables and output parameters at the beginning of the
procedure
• They increase the readability and maintainability of the code
• Use comments – lots of comments!
• Use indentation consistently
• Label all blocks – compound blocks as well as IF, WHILE, etc
6
Compound Statements (aka Compound Blocks)
• A compound statement contains a block of the following:
• Optional label
• BEGIN keyword
• Declarations for:
• SQL Variables
• SQL Conditions
• Return Codes
• Statements
• Cursors
• Handlers
• SQL statements
• END keyword
• Optional label
IBM Insight 2014
7
Nested Compound Statements (aka Nested Compound Blocks)
• Nested compound statements help to further define the
scope of variables, conditions, handlers, cursors, etc to a
subset of statements in a procedure
• Nested compound statements allow compound statements
to be used in handlers
CREATE PROCEDURE <procedure name> (<parameter list>)
…
OuterMostBlock:
BEGIN
END OuterMostBlock;
InnermostBlock:
BEGIN
END InnermostBlock;
InnerBlock1:
BEGIN
END InnerBlock1;
InnerBlock2:
BEGIN
END InnerBlock2;
8
Using Templates – Specific Ordering
-- native SQL PL procedure template
CREATE PROCEDURE <procedure name> (<parameter list>)
VERSION <version id>
LANGUAGE SQL
<option list>
OuterMostBlock:
BEGIN
-----------------------------------------------------------------------------
-- SQL Variable, SQL Condition, Return Code Declarations --
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
-- Statement Declarations --
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
-- DECLARE CURSOR Statements --
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
-- Handler Declarations --
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
-- SQL Procedure Statements --
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
-- Init all output parameters --
-------------------------------------------------------------------------------------
END OuterMostBlock;
May be any number of
compound blocks itself
Use DEFAULT
values for all
SQL Variables
MUST specify
items in this
order
IN, INOUT, OUT,
OUT Out_Return_Code
Declare SQLCODE
and SQLSTATE
variables
IBM Insight 2014
9
Using Templates – Standardized Handlers
CREATE PROCEDURE <procedure name>
(…, OUT Out_SQLCODE INTEGER,
OUT Out_DiagString VARCHAR(32000),
OUT Out_WarnCount INTEGER,
OUT Out_TMS TIMESTAMP)
….
OuterMostBlock: BEGIN
….
--------------------------------------------------------------------------------
-- Condition Declarations --
--------------------------------------------------------------------------------
DECLARE WARN_AND_EXIT CONDITION FOR
SQLSTATE '80000';
DECLARE ERR_AND_EXIT CONDITION FOR
SQLSTATE '90000';
--------------------------------------------------------------------------------
-- Handler Declarations --
--------------------------------------------------------------------------------
-- Handler declarations for user-defined conditions
DECLARE EXIT HANDLER FOR WARN_AND_EXIT
BEGIN
SET Out_SQLCODE = SQLCODE;
SET Out_DiagString = ‘Warning hit in STP’;
SET Out_TMS = CURRENT TIMESTAMP;
END;
DECLARE EXIT HANDLER FOR ERR_AND_EXIT
BEGIN
SET Out_SQLCODE = SQLCODE;
SET Out_DiagString = ‘Error hit in STP’;
SET Out_TMS = CURRENT TIMESTAMP;
END;
…
-- Handler declarations for generic conditions
DECLARE EXIT HANDLER FOR SQLEXCEPTION
SQLException_Exit_Handler: BEGIN
--SELECT SQLCODE INTO Out_SQLCODE
--FROM SYSIBM.SYSDUMMY1;
--SET Out_SQLCODE = SQLCODE;
SET Out_SQLCODE = SQLCODE;
GET DIAGNOSTICS Out_DiagString = ALL STATEMENT;
END SQLException_Exit_Handler;
DECLARE CONTINUE HANDLER FOR SQLWARNING
SQLWarning_Continue_Handler: BEGIN
SET Out_WarnCount = Out_WarnCount + 1;
END SQLWarning_Continue_Handler;
DECLARE CONTINUE HANDLER FOR NOT FOUND
NotFound_Continue_Handler: BEGIN
SET xEOF_Reached = 1;
END NotFound_Continue_Handler;
….
END OuterMostBlock;
10
Naming Resolution Rules (Variables, Columns, Etc)
• Qualify, qualify, qualify!
Qualify column names with table names
Qualify SQL parameters by procedure name
Qualify SQL variables by label of the compound statement
• If no qualification or ambiguous qualification exists:
The name is checked to see if it is the name of a column of any
existing table or a view that is specified in the SQL routine body at
the current server
If the referenced tables or views do not exist at the current server,
the name will be checked first as an SQL variable name in the
compound statement and then as an SQL parameter name.
IBM Insight 2014
11
Confusing Naming Resolution Example
CREATE PROCEDURE NamingProc (INOUT RESULT INTEGER)
…
OuterMostBlock:
BEGIN
DECLARE AMOUNT INTEGER DEFAULT 100;
…
InnerBlock1:
BEGIN
DECLARE AMOUNT INTEGER DEFAULT 0;
IF RESULT < 0 THEN
UPDATE Product_Table SET AMOUNT = AMOUNT;
ELSE
SET AMOUNT = 50;
SELECT AMOUNT INTO AMOUNT
FROM Product_Table WHERE AMOUNT < RESULT;
END InnerBlock1;
SET RESULT = AMOUNT;
END OuterMostBlock;
CREATE TABLE Product_Table (AMOUNT INTEGER,
RESULT INTEGER,
…);
Can only resolve to
RESULT parameter Q: Resolve to
column or
variable?
Q: Resolve to
variable or
parameter?
Q: Resolve to
column or
variable?
Q: Resolve to
column or
variable?
Can only resolve to
RESULT parameter and
OuterMostBlock AMOUNT
variable
12
Explicitly Qualified Naming Resolution Example
CREATE PROCEDURE NamingProc (INOUT RESULT INTEGER)
…
OuterMostBlock:
BEGIN
DECLARE AMOUNT INTEGER DEFAULT 100;
…
InnerBlock1:
BEGIN
DECLARE AMOUNT INTEGER DEFAULT 0;
IF NamingProc.RESULT < 0 THEN
UPDATE Product_Table SET Product_Table.AMOUNT = InnerBlock1.AMOUNT;
ELSE
SET OuterMostBlock.AMOUNT = 50;
SELECT Product_Table.AMOUNT INTO InnerBlock1.AMOUNT
FROM Product_Table WHERE OuterMostBlock.AMOUNT < Product_Table.RESULT;
END InnerBlock1;
SET NamingProc.RESULT = OuterMostBlock.AMOUNT;
END OuterMostBlock;
CREATE TABLE Product_Table (AMOUNT INTEGER,
RESULT INTEGER,
…);
IBM Insight 2014
13
Dynamic SQL – Generic handling
CREATE PROCEDURE DYNAMIC_STMNT (IN IN_SCHEMA CHAR(10),
IN IN_SQL_TXT VARCHAR(32000), … )
VERSION Y2014M10D01
LANGUAGE SQL
DYNAMIC RESULT SETS 1
MODIFIES SQL DATA
QUALIFIER QUAL1
SQL PATH PATH1, PATH2, PATH3
ISOLATION LEVEL UR
VALIDATE BIND
DYNAMICRULES RUN
DISALLOW DEBUG MODE
ASUTIME LIMIT 10000
MAIN_LOGIC:
BEGIN
…
-- DECLARE CURSOR Statements --
DECLARE ADHOC_CSR CURSOR WITH RETURN FOR ADHOC_STMT;
…
-- SQL Procedure Statements --
SET CURRENT SCHEMA = IN_SCHEMA;
PREPARE ADHOC_STMT FROM IN_SQL_TXT;
OPEN ADHOC_CSR;
END MAIN_LOGIC;
Objects and privileges
must exist at CREATE
PROCEDURE time or
CREATE fails
Don’t allow debugging
on Production system
CPU threshold for
proc execution
14
Dynamic SQL – Build SQL based on input parameters
CREATE PROCEDURE DYNAMIC_STMNT
(IN IN_ID CHAR(10),
IN IN_NAME VARCHAR(20),…
OUT OUT_SQLCODE CHAR(5),
OUT OUT_DIAGSTRING VARCHAR(32000),
OUT OUT_END_TMS TIMESTAMP,
OUT OUT_ID_IND CHAR(1), …)
VERSION Y2014M10D01
LANGUAGE SQL
DYNAMIC RESULT SETS 1
…
MAIN_LOGIC:
BEGIN
-- SQL Variable, SQL Condition, Return Code Declarations –
DECLARE V_SELECTSTMT VARCHAR(4000);
DECLARE ERR_AND_EXIT CONDITION FOR SQLSTATE '90000';
…
-- DECLARE CURSOR Statements --
DECLARE C_CURSOR1 CURSOR
WITH RETURN FOR S_STATEMENT;
…
-- Handler Declarations --
DECLARE EXIT HANDLER FOR ERR_AND_EXIT
BEGIN
SET OUT_END_TMS = CURRENT TIMESTAMP;
END;
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
SET OUT_SQLCODE = SQLCODE;
GET DIAGNOSTICS OUT_DIAGSTRING = ALL STATEMENT;
END SQLException_Exit_Handler;
-- SQL Procedure Statements
-- Initialize Output Parms
SET OUT_ID_IND = ‘Y’;
VALIDATE_INPUT: BEGIN
IF (IN_ID IS NULL ) THEN
SET OUT_ID_IND = 'N';
SIGNAL ERR_AND_EXIT;
END IF;
END VALIDATE_INPUT;
BUILD_SQL_TEXT: BEGIN
SET V_SELECTSTMT =
'SELECT T1.ID ‘ ||
‘ ,T1.NAME '||
' FROM T1‘ ||
' WHERE ‘ ||
‘T1.ID = IN_ID‘;
IF (IN_NAME IS NOT NULL ) THEN
SET V_SELECTSTMT = V_SELECTSTMT ||
' AND T1.NAME ='''|| IN_NAME ||''';
END BUILD_SQL_TEXT;
PREPARE S_STATEMENT FROM V_SELECTSTMT ;
OPEN C_CURSOR1;
SET OUT_END_TMS = CURRENT TIMESTAMP;
END MAIN_LOGIC;
IBM Insight 2014
15
XML Parameters and Variables
• XML is available as a procedure parameter or as an SQL
variable inside a Native SQL Procedure
CREATE PROCEDURE XMLPROC(IN IN_XMLPARM XML, IN VCHPARM VARCHAR(32000))
LANGUAGE SQL
BEGIN
DECLARE myXMLVar XML;
IF (XMLEXISTS('$x/ITEM[value < 200]' passing by ref IN_XMLPARM as "x")) THEN
INSERT INTO T1 VALUES(IN_XMLPARM);
END IF;
SET myXMLVar =
XMLDOCUMENT(XMLELEMENT(NAME "ORDER",
XMLCONCAT(PARM1, IN_XMLPARM)));
INSERT INTO T1 VALUES(myXMLVar);
END #
16
Array Data Type Overview
• DB2 for z/OS introduces support for Arrays inside SQL
Routines (UDF or Procedure).
• Prior to DB2 11, users might have utilized the following
mechanisms to pass data to/from Routines:
• DECLARED GLOBAL TEMPORARY TABLE,
• Concatenated Strings,
• Long lists of parameters, or …
• The Array Data Type consists of an ordered set of elements
having the same data type (length, precision, scale, CCSID as
appropriate)
• Two Types of Arrays are Supported:
• Ordinary Arrays
• Have a maximum cardinality (2 Billion)
• The data type of the index value is INTEGER
• Associative Arrays
• Do not have a defined upper bound on the number of elements
• The data type of the index values can be an INTEGER or character string (not a LOB)
• Think of arrays as light-weight workfiles
V11
IBM Insight 2014
17
Native SQL Procedure Processing with Arrays
z/OS
Appl pgm DB2
DBM1
DDF
EDM pool
SQL PL native logic
SQL
SQL
ArraySP
Java pgm
…
CALL ArraySP
EDM pool
SQL PL native logic
SQL
CALL ArraySP
ArraySPCaller
CALL ArraySPCaller
1a*
1b
2
*T4 Driver Only, CALL stmt Only
*native SQL procedures do not run IN the WLM address space but are still running UNDER the WLM; NSPs take on the caller’s WLM priority
V11
18
Populating a table from Arrays
CREATE PROCEDURE NEW_PRODUCT_INFO ( )
….
LANGUAGE SQL
MAIN_LOGIC:
BEGIN
…
-----------------------------------------------------------------------------
-- SQL Variable, SQL Condition, Return Code Declarations --
-------------------------------------------------------------------------------------
DECLARE MYSKUARRAY CHA10ARRAY;
DECLARE MYPRICEARRAY DEC92ARRAY;
…
-------------------------------------------------------------------------------------
-- SQL Procedure Statements --
-------------------------------------------------------------------------------------
-- construct an array with new SKU values
SET MYSKUARRAY = ARRAY['sku99','sku01','sku20','sku04'];
-- construct a 2nd array with new PRICE values
SET MYPRICEARRAY = ARRAY[99.00, 1.99, 20.98, 4.96];
-- populate table with values from arrays
INSERT INTO PRODUCT (SKU, PRICE)
SELECT *
FROM UNNEST(MYSKUARRAY,MYPRICEARRAY) AS T(NEW_SKU,NEW_PRICE) ;
END MAIN_LOGIC;
PRODUCT
1.99sku01
20.98sku20
4.96Sku04
SKU PRICE
sku99 99.00
Result table
V11
IBM Insight 2014
19
Appending elements to an Array – Solution 1
CREATE PROCEDURE NEW_PRODUCT_INFO ( )
….
LANGUAGE SQL
MAIN_LOGIC:
BEGIN
…
-------------------------------------------------------------------------------------
-- SQL Procedure Statements --
-------------------------------------------------------------------------------------
-- populate 1st array with NAMEs
SET MYVCHARRAY1 = (SELECT ARRAY_AGG(NAME) FROM FRIENDS);
-- populate 2nd array with TELEs
SET MYVCHARRAY2 = (SELECT ARRAY_AGG(TELE) FROM FRIENDS);
-- determine number of elements in 1st array
SET IDX = CARDINALITY(MYVCHARRAY1);
-- loop over all elements in 2nd array
WHILE LCV <= CARDINALITY(MYVCHARRAY2) DO
-- assign elements from 2nd array into 1st array
SET MYVCHARRAY1[IDX + LCV] = MYVCHARRAY2[LCV];
SET LCV = LCV + 1;
END WHILE;
-- verify results
INSERT INTO RESULT_TB(INFO)
SELECT * FROM UNNEST(MYVCHARRAY1) AS T(VALUE);
END MAIN_LOGIC;
Result table
FRIENDS
555-1212Meg
555-1313Sarbinder
NAME TELE
Chris 555-1111
Chris
Meg
Sarbinder
555-1111
555-1212
555-1313
RESULT_TB
INFO
V11
20
Appending elements to an Array – Solution 2
…
MAIN_LOGIC:
BEGIN
…
-------------------------------------------------------------------------------------
-- SQL Procedure Statements --
-------------------------------------------------------------------------------------
-- populate 1st array
SET MYVCHARRAY1 = (SELECT ARRAY_AGG(NAME) FROM FRIENDS);
-- populate result table
INSERT INTO RESULT_TB(INFO)
SELECT * FROM UNNEST(MYVCHARRAY1) AS T(VALUE);
INSERT INTO RESULT_TB(INFO) VALUES('**********');
-- populate 2nd array
SET MYVCHARRAY2 = (SELECT ARRAY_AGG(TELE) FROM FRIENDS);
-- 'add 2nd array to 1st array'
SET MYVCHARRAY1 = (SELECT ARRAY_AGG(VAL.RESULT)
FROM TABLE (SELECT T.VALUE AS RESULT
FROM UNNEST(MYVCHARRAY1) AS T(VALUE)
UNION ALL
SELECT T.VALUE AS RESULT
FROM UNNEST(MYVCHARRAY2) AS T(VALUE)) AS VAL);
-- populate result table
INSERT INTO RESULT_TB(INFO) SELECT * FROM UNNEST(MYVCHARRAY1) AS T(VALUE);
END MAIN_LOGIC;
FRIENDS
555-1212Meg
555-1313Sarbinder
NAME TELE
Chris 555-1111
Chris
Meg
Sarbinder
Chris
Meg
Sarbinder
**********
555-1111
555-1212
555-1313
RESULT_
TB
INFO
V11
IBM Insight 2014
21
Appending elements to an Array – Solution 3
CREATE FUNCTION APPEND_ARRAY(ARR1 INTARRAYTYPE, ARR2 INTARRAYTYPE)
RETURNS INTARRAYTYPE
BEGIN
DECLARE COUNTER INT DEFAULT 1;
IF ARR2 IS NULL OR CARDINALITY(ARR2) = 0 THEN
RETURN ARR1;
END IF;
SET ARR1 = (SELECT ARRAY_AGG(TX.C1 ORDER BY TX.ID) FROM
(SELECT U.C1,U.ID
FROM UNNEST(ARR1) WITH ORDINALITY AS U(C1,ID)
UNION ALL
SELECT V.C1,V.ID + CARDINALITY(ARR1)
FROM UNNEST(ARR2) WITH ORDINALITY AS V(C1,ID) ) TX(C1,ID)) ;
END IF;
RETURN ARR1;
END#
CREATE PROCEDURE PRCAP()
DYNAMIC RESULT SETS 1
…
MAIN_LOGIC:
BEGIN
…
DECLARE ARR1,ARR2 INTARRAYTYPE;
…
DECLARE C1 CURSOR WITH RETURN FOR
SELECT U.C1 FROM UNNEST(ARR1) AS U(C1);
SET ARR1=(SELECT ARRAY_AGG(INT(SALARY)) FROM EMP);
SET ARR2=(SELECT ARRAY_AGG(INT(SALARY)) FROM EMP);
SET ARR1= APPEND_ARRAY(ARR1,ARR2);
OPEN C1;
END MAIN_LOGIC;
V11
22
Passing sets of values –
Comma Delimited Concatenated Strings
CREATE PROCEDURE NONARRAY1IN1OUT (IN IN_ARRAY VARCHAR(1000),
OUT OUT_ARRAY VARCHAR(1000))
MAIN_LOGIC:
BEGIN
…
-- declare a cursor that invokes a UDF that parses the comma delimited input string
DECLARE ARRAYINCUR CURSOR FOR
SELECT I_PRICE
FROM ITEM, TABLE(String2Set(IN_ARRAY,',')) AS T(DAT)
WHERE I_ID = T.DAT
FOR FETCH ONLY;
OPEN ARRAYINCUR ;
WHILE (MAIN_LOGIC.EOD = 0 ) DO
-- assign local variable to Nth value in comma delimited input string
FETCH FROM ARRAYINCUR INTO MAIN_LOGIC.PRICE;
IF (MAIN_LOGIC.EOD = 0) THEN
-- build comma delimited output string
SET OUT_ARRAY = OUT_ARRAY || RTRIM(CHAR(MAIN_LOGIC.PRICE)) || ',' ;
END IF;
END WHILE ;
CLOSE ARRAYINCUR ;
END MAIN_LOGIC;
Returns data based on Parsed
Input String Values
Treat the Input String Like a Table
i.e. 1 string from delimited string
= 1 row
V11
IBM Insight 2014
23
Passing sets of values – Arrays
CREATE PROCEDURE ARRAY1IN1OUT (IN IN_IDARRAY IDARRAY_TYPE,
OUT OUT_PRICEARRAY PRICEARRAY_TYPE)
LANGUAGE SQL
MAIN_LOGIC:
BEGIN
…
-- build output array by selecting values directly from table based on input array values
SELECT ARRAY_AGG(I_PRICE) INTO OUT_PRICEARRAY
FROM (SELECT I_PRICE
FROM ITEM, (SELECT ID
FROM UNNEST(IN_IDARRAY) AS ITEMID (ID)) AS ITEMID
WHERE I_ID = ITEMID.ID) AS TB
FETCH FIRST 1 ROW ONLY;
END MAIN_LOGIC;
Accepts an Array as Input
Returns an Array as Output
Returns data based on Input
Array Values
Treat an Array like a Table
i.e. 1 element = 1 row
V11
24
Invoke Native SQL Proc with Array Parms (Java)
import java.sql.Array;
…
public class ArrayTest
{
…
private void run () throws SQLException {
String[] param = new String [20]; // create string variable
for (int i = 0; i < ARRAY_COUNT; i++) { param [i] = ""+i; } // init string variable
try {
java.sql.Array inParam = con.createArrayOf ("VARCHAR", param); // create Array of VARCHAR elements
CallableStatement cs = con.prepareCall("CALL ArraySP(?,?)"); // prepare CALL stmt
cs.setArray (1, inParam); // indicate Input parm (Parm1) is an Array
cs.registerOutParameter (2, java.sql.Types.ARRAY); // indicate Output parm (Parm2) is an Array
cs.execute (); // call the STP
Array outArray = cs.getArray (2); // get Output parm data
String[] AOut = (String [])outArray.getArray(); // obtain string representation
for(int i = 0; i < AOut.length; i++) { System.out.println(AOut[i]); } // print result
cs.close ();
con.close ();
} …
}
…
public static void main (String[] args) {
ArrayTestVchAll sc = new ArrayTest();
try { sc.run (); } … } }
-- snippet of create procedure statement
CREATE PROCEDURE ArraySP (IN InP1 OrdVchArray,
OUT OutP1 OrdVchArray)
BEGIN
…
END;
V11
IBM Insight 2014
25
Global Variables
• Benefits
• Allows users to share information across SQL statements
• Allows capability to set once, use everywhere
• Provides additional security via DB2 GRANT and REVOKE
• Characteristics
• Similar to special registers
• Their definitions are global and shared across different
connections
• Their contents are only shared within the same connection
• Each connection maintains its own instantiation
• Their contents are NOT affected by COMMIT nor ROLLBACK
• Use only the UNICODE encoding scheme
V11
26
Using and Referencing a Global Variable
-- create a global variable
CREATE VARIABLE Charge_Rate DECIMAL(4,2) DEFAULT 0.00;
-- create a procedure that determines charge rate
CREATE PROCEDURE Loan_Charge_Rate (IN ID CHAR(5))
LANGUAGE SQL
BEGIN
..
SELECT SCORE INTO Cust_Score FROM CUSTOMER WHERE ACCOUNT = ID;
IF Cust_Score = ‘Good’ THEN SET Charge_Rate = 1.0;
ELSE SET Charge_Rate = 3.0;
END;
-- calling application
myApp: PROCEDURE(Buyer, Amount);
…
CALL Loan_Charge_Rate(Buyer);
UPDATE CUSTOMER SET BALANCE = BALANCE + (Amount * Charge_Rate);
END myAPP;
Referencing
the GV
Setting the
GV
V11
IBM Insight 2014
27
Autonomous Transactions
• An Autonomous Transactions is:
• A native SQL procedure that runs in its own unit of work
• May perform SQL, COMMITs, and ROLLBACK it’s own SQL
• No uncommitted changes from it’s caller are seen
• Locks are not shared between the caller and the autonomous
procedure
• Upon completion of the autonomous procedure, a COMMIT is
driven for the autonomous procedure when SQLCODE >=0
• The caller’s work is untouched
• Useful for event or audit logs
V11
28
Error Logging Example
Appl_pgm:
…
INSERT INTO T1 …
IF SQLCODE < 0 THEN
CALL ErrorLog_Proc;
ROLLBACK;
…
End Appl_pgm;
CREATE PROCEDURE ErrorLog_Proc ()
LANGUAGE SQL
AUTONOMOUS
Main_Logic:
BEGIN
…
INSERT INTO T2 …
…
END Main_Logic;
• T1 modifications are unseen by the Autonomous
Transaction ErrorLog_Proc
• After successful execution of the Autonomous Transaction
ErrorLog_Proc, T2 changes are committed by not T1
changes
New keyword to allow
NSP to run it it’s own
unit of work
V11
IBM Insight 2014
29
Developing SQL PL Routines with Data Studio
• Full DB2 V11 support
• SQL PL Routines Development
Stores commonly used patterns as reusable templates
Validates SQL PL statements in the editor
Deploys stored procedure to multiple servers
Steps through routines and inspects variables with
graphical debugger
29
30
Tuning and Testing with Data Studio
• SQL Tuning
Displays Access Plan visually
Runs Statistics Advisor on single query
• Regression Testing
Compares routines output with base line
30
IBM Insight 2014
33
Debugging a Routine
34
What about Functions?
• Functions may also be written in SQL PL
• May contain logic using SQL PL control statements
• SQL functions are non-inline i.e. package is created
• Parser determines type of function
• Example – Reverse a string
CREATE FUNCTION REVERSE(INSTR VARCHAR(20))
RETURNS VARCHAR(20)
DETERMINISTIC NO EXTERNAL ACTION CONTAINS SQL
BEGIN
DECLARE REVSTR, RESTSTR VARCHAR(20) DEFAULT '';
DECLARE LEN INT;
IF INSTR IS NULL THEN
RETURN NULL;
END IF;
SET (RESTSTR, LEN) = (INSTR, LENGTH(INSTR));
WHILE LEN > 0 DO
SET (REVSTR, RESTSTR, LEN) =
(SUBSTR(RESTSTR, 1, 1) CONCAT REVSTR,
SUBSTR(RESTSTR, 2, LEN - 1),
LEN - 1);
END WHILE;
RETURN REVSTR;
END
compiled SQL
scalar functions
IBM Insight 2014
35
Summary
• Standardize coding practices by creating universal templates
• Create a generic procedure to execute dynamic SQL
• Provide greater flexibility of data exchange with global
variables
• Consider native SQL PL procedures for new workloads as the
array data type and autonomous transactions provide even
greater usability
36
Websites
• Requirements
https://www.ibm.com/developerworks/rfe/
• DB2 for z/OS Knowledge Center
http://www-
01.ibm.com/support/knowledgecenter/SSEPEK/db2z_
prodhome.html
• DB2 11 for z/OS Technical Overview Redbook
http://publibb.boulder.ibm.com/abstracts/sg248180.html?Open
• DB2 9 for z/OS Stored Procedures: Through the
CALL and Beyond Redbook
http://www.redbooks.ibm.com/abstracts/sg247604.html?Open
IBM Insight 2014
37
Maryela Weihrauch
IBM Corporation, Silicon Valley Laboratory
weihrau@us.ibm.com
Meg Bernal
IBM Corporation, Silicon Valley Laboratory
meg@us.ibm.com
38
We Value Your Feedback!
• Don’t forget to submit your Insight session and speaker feedback!
Your feedback is very important to us – we use it to continually
improve the conference.
• Access the Insight Conference Connect tool to quickly submit your
surveys from your smartphone, laptop or conference kiosk.
38