This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
IBM Insight 2014
SQL PL for DB2 for z/OS Application Developers –Programming Tips for Simplifying ApplicationsSession Number IDZ-4219D
Maryela Weihrauch, Distinguished Engineer IBM Corporation, Silicon Valley Laboratory
Meg Bernal, Senior Software Engineer IBM Corporation, Silicon Valley Laboratory
• Quick Overview of SQL PL Procedures• Existing Functionality
• Compound Blocks
• Templates
• Naming Resolution Rules
• Dynamic SQL
• XML Support
• DB2 11 Enhancements• Array Data Type Support
• Global Variables
• Autonomous Transactions
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
• 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
� 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 ExampleCREATE PROCEDURE NamingProc (INOUT RESULT INTEGER)…OuterMostBlock:BEGIN
DECLARE AMOUNT INTEGER DEFAULT 100;…InnerBlock1:
BEGINDECLARE AMOUNT INTEGER DEFAULT 0;
IF RESULT < 0 THENUPDATE Product_Table SET AMOUNT = AMOUNT;
ELSESET 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:
BEGINDECLARE AMOUNT INTEGER DEFAULT 0;
IF NamingProc.RESULT < 0 THENUPDATE Product_Table SET Product_Table.AMOUNT = InnerBlock1.AMOUNT;
ELSESET 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 handlingCREATE PROCEDURE DYNAMIC_STMNT (IN IN_SCHEMA CHAR(10),
IN IN_SQL_TXT VARCHAR(32000), … )VERSION Y2014M10D01LANGUAGE SQLDYNAMIC RESULT SETS 1MODIFIES SQL DATA QUALIFIER QUAL1SQL PATH PATH1, PATH2, PATH3ISOLATION LEVEL URVALIDATE BINDDYNAMICRULES RUNDISALLOW DEBUG MODEASUTIME LIMIT 10000MAIN_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 parametersCREATE 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 Y2014M10D01LANGUAGE SQLDYNAMIC 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_EXITBEGIN
SET OUT_END_TMS = CURRENT TIMESTAMP;END;
DECLARE EXIT HANDLER FOR SQLEXCEPTIONBEGINSET OUT_SQLCODE = SQLCODE;GET DIAGNOSTICS OUT_DIAGSTRING = ALL STATEMENT;
IF (IN_NAME IS NOT NULL ) THENSET 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")) THENINSERT 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/OSAppl pgm DB2
DBM1DDF
EDM pool
SQL PL native logicSQLSQL
ArraySP
Java pgm…
CALL ArraySP
EDM pool
SQL PL native logicSQL
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 SQLMAIN_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 1CREATE PROCEDURE NEW_PRODUCT_INFO ( )….LANGUAGE SQLMAIN_LOGIC: BEGIN…--------------------------------------------------------------------------------------- SQL Procedure Statements ----------------------------------------------------------------------------------------- populate 1st array with NAMEsSET MYVCHARRAY1 = (SELECT ARRAY_AGG(NAME) FROM FRIENDS); -- populate 2nd array with TELEsSET MYVCHARRAY2 = (SELECT ARRAY_AGG(TELE) FROM FRIENDS); -- determine number of elements in 1st arraySET IDX = CARDINALITY(MYVCHARRAY1);
-- loop over all elements in 2nd arrayWHILE 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 TELEChris 555-1111
Chris
Meg
Sarbinder
555-1111
555-1212
555-1313
RESULT_TBINFO
V11
20
Appending elements to an Array – Solution 2…MAIN_LOGIC: BEGIN…--------------------------------------------------------------------------------------- SQL Procedure Statements ----------------------------------------------------------------------------------------- populate 1st arraySET 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 arraySET MYVCHARRAY2 = (SELECT ARRAY_AGG(TELE) FROM FRIENDS);
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 TELEChris 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 3CREATE FUNCTION APPEND_ARRAY(ARR1 INTARRAYTYPE, ARR2 INTARRAYTYPE)RETURNS INTARRAYTYPEBEGIN
DECLARE COUNTER INT DEFAULT 1;
IF ARR2 IS NULL OR CARDINALITY(ARR2) = 0 THENRETURN 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 ALLSELECT 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 FORSELECT 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 stringDECLARE ARRAYINCUR CURSOR FORSELECT I_PRICE FROM ITEM, TABLE(String2Set(IN_ARRAY ,',')) AS T(DAT) WHERE I_ID = T.DATFOR FETCH ONLY;
OPEN ARRAYINCUR ;
WHILE (MAIN_LOGIC.EOD = 0 ) DO-- assign local variable to Nth value in comma delimited input stringFETCH FROM ARRAYINCUR INTO MAIN_LOGIC.PRICE;
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 SQLMAIN_LOGIC: BEGIN
…-- build output array by selecting values directly from table based on input array valuesSELECT ARRAY_AGG (I_PRICE) INTO OUT_PRICEARRAYFROM (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 InputReturns 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 stmtcs.setArray (1, inParam); // indicate Input parm (Parm1) is an Array cs.registerOutParameter (2, java.sql.Types.ARRAY); // indicate Output parm (Parm2) is an Arraycs.execute (); // call the STPArray outArray = cs.getArray (2); // get Output parm data String[] AOut = (String [])outArray.getArray(); // obtain string representationfor(int i = 0; i < AOut.length; i++) { System.out.println(AOut[i]); } // print resultcs.close (); con.close ();
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
IBM Insight 2014
39
Acknowledgements and Disclaimers Availability . References in this presentation to IBM products, programs, or services do not imply that they will be available in all countries in which IBM operates.
The workshops, sessions and materials have been prepared by IBM or the session speakers and reflect their own views. They are provided for informational purposes only, and are neither intended to, nor shall have the effect of being, legal or other guidance or advice to any participant. While efforts were made to verify the completeness and accuracy of the information contained in this presentation, it is provided AS-IS without warranty of any kind, express or implied. IBM shall not be responsible for any damages arising out of the use of, or otherwise related to, this presentation or any other materials. Nothing contained in this presentation is intended to, nor shall have the effect of, creating any warranties or representations from IBM or its suppliers or licensors, or altering the terms and conditions of the applicable license agreement governing the use of IBM software.
All customer examples described are presented as illustrations of how those customers have used IBM products and the results they may have achieved. Actual environmental costs and performance characteristics may vary by customer. Nothing contained in these materials is intended to, nor shall have the effect of, stating or implying that any activities undertaken by you will result in any specific sales, revenue growth or other results.
— U.S. Government Users Restricted Rights – Use, dupli cation or disclosure restricted by GSA ADP Schedule Co ntract with IBM Corp.
IBM, the IBM logo, ibm.com, and DB2 are trademarks or registered trademarks of International Business Machines Corporation in the United States, other countries, or both. If these and other IBM trademarked terms are marked on their first occurrence in this information with a trademark symbol (® or TM), these symbols indicate U.S. registered or common law trademarks owned by IBM at the time this information was published. Such trademarks may also be registered or common law trademarks in other countries. A current list of IBM trademarks is available on the Web at
•“Copyright and trademark information” at www.ibm.com/legal/copytrade.shtml
•Other company, product, or service names may be trademarks or service marks of others.