0% found this document useful (0 votes)
11 views

Writing SQL Stored Procedures and Functions

Store Procedure DB2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Writing SQL Stored Procedures and Functions

Store Procedure DB2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

1/14/2017

SQL Procedures
(and Functions and Triggers)

Rob Bestgen
[email protected]
IBM - DB2 for i Consultant

© 2017 IBM Corporation

IBM Power Systems

SQL as a development language

SQL is a well established, standardized language for database access

SQL is also a programming language!

 SQL/PSM (https://en.wikipedia.org/wiki/SQL/PSM) is a full procedural


programming language

 PSM enhances portability


– Supported across DB2 Family
– Similar to proprietary DBMS procedure languages (PL/SQL, T-SQL, etc…)

Makes it easier for SQL programmers to be productive faster on IBM i

2 © 2017 IBM Corporation


M
IB

1
1/14/2017

IBM Power Systems

Supported languages
DB2 for i supports two types of procedures/functions/triggers

1. SQL
• Coded entirely with SQL following (PSM) Standard
• Allows full suite of SQL statements

2. External
• Register a high-level language program (RPG, COBOL, Java, C…) for
subsequent calls from SQL**
• may or may not use SQL within the program itself

** Non-SQL triggers use CL command ADDPFTRG

3 © 2017 IBM Corporation

IBM Power Systems

Supported languages
DB2 for i supports two types of procedures/functions/triggers

1. SQL
• Coded entirely with SQL following (PSM) Standard
• Allows full suite of SQL statements

2. External
• Register a high-level language program (RPG, COBOL, Java, C…) for
subsequent calls from SQL**
• may or may not use SQL within the program itself

SQL is the main focus here

** Non-SQL triggers use CL command ADDPFTRG

4 © 2017 IBM Corporation


M
IB

2
1/14/2017

IBM Power Systems

SQL Routines
Comparison of SQL Routine types
 Procedures
– Similar to high-level language program, facilitates reuse of common logic
– Usage is similar to any program
– Frequently used as the backend ‘service’ to application calls e.g. REST calls
 Lessen network traffic
 Secure data access
– Can also return result sets of data
 Functions (user-defined)
– Returns a result each time it is invoked
– Frequently invoked from within an SQL query
SELECT myfunc1() FROM mytable WHERE myfunc2(col1)>100

 Triggers
– Attached to a file/table. Invoked for data changes
– Automatically invoked by DB2 when necessary, regardless of interface

5 © 2017 IBM Corporation

IBM Power Systems

SQL Routines…

Each time an SQL Routine is created, DB2 for i uses the SQL
procedural source to generate a C program (or srvpgm) object
– Developer does not need to know C code
– C compiler purchase is not required
– Like other pgms, IBM i security model and adopted authorities apply

CREATE PROCEDURE proc1 (IN Emp# CHAR(4),IN NwLvl INT)


LANGUAGE SQL
BEGIN
DECLARE CurLvl INT;
SELECT edlevel INTO CurLvl FROM emptbl
WHERE empno=Emp#;

IF NwLvl > CurLvl THEN


UPDATE emptbl SET edlevel=NwLvl,
salary=salary + (salary*0.05) WHERE empno=Emp#;
END IF;
END
6 © 2017 IBM Corporation
M
IB

3
1/14/2017

IBM Power Systems

Procedure
1 Create it
CREATE OR REPLACE PROCEDURE total_val (IN Member# CHAR(6),
OUT total DECIMAL(12,2))
LANGUAGE SQL
BEGIN
SELECT SUM(curr_balance) INTO total
FROM accounts
WHERE account_owner=Member# AND
account_type IN ('C','S','M');
END

2 CALL it from an SQL interface


CALL total_val(‘123456’, :balance)

7 © 2017 IBM Corporation

IBM Power Systems

Function
Two types:
1. Scalar function
– Returns a single value
– Invoked from almost any SQL statement
– Good for encapsulating complex operations or calculations

2. Table function
– Returns a set of rows with columns
• A dynamic table!
– Invoked from an SQL query or view (FROM clause)
– Good for encapsulating non-traditional data or complex operations

 CREATE FUNCTION SQL statement to create

 Reference directly or wrap in TABLE statement to invoke*

* TABLE statement for table functions

8 © 2017 IBM Corporation


M
IB

4
1/14/2017

IBM Power Systems

Scalar Function
1 Create it (one time)

CREATE OR REPLACE FUNCTION Discount(totalSales DECIMAL(11,2))


RETURNS DECIMAL(11,2)
LANGUAGE SQL DETERMINISTIC
BEGIN
IF totalSales>10000 THEN
RETURN totalSales*.9;
ELSE
RETURN totalSales;
END IF;
END

2 Call it from an SQL query or statement


SELECT SUM(sales), Discount( SUM(sales) ) FROM mysales…

9 © 2017 IBM Corporation

IBM Power Systems

Table Function
1 Create it (one time)

CREATE FUNCTION bestSales (BonusThreshold DECIMAL(11,2))


RETURNS TABLE (Empid INT,
LastName VARCHAR(30),
FirstName VARCHAR(30))
LANGUAGE SQL
READS SQL DATA
RETURN
SELECT id, lname, fname FROM custsales
GROUP BY id, lname, fname
HAVING SUM(sales)>BonusThreshold

2 Call it from an SQL query or statement


SELECT LastName, Empid from TABLE(bestSales(100000)) T1

10 © 2017 IBM Corporation


M
IB

5
1/14/2017

IBM Power Systems

Trigger
A program called when a row(s) in a table or file change
 Associated with a table (or view)
 Invoked automatically by DB2 when a row changes

When do you need triggers?


 Consistently enforce business rules
 Monitor critical tables

CREATE TRIGGER SQL statement to create and register*

* ADDPFTRG CL command for external triggers

11 © 2017 IBM Corporation

IBM Power Systems

SQL Trigger Examples


CREATE TRIGGER protect_salary
BEFORE UPDATE OF salary ON employee
REFERENCING NEW AS n OLD AS o
FOR EACH ROW
WHEN (n.salary> 1.5 * o.salary)
SET n.salary = 1.5 * o.salary;

CREATE TRIGGER big_spenders


AFTER INSERT ON expenses
REFERENCING NEW ROW AS n
FOR EACH ROW
BEGIN
DECLARE emplname CHAR(30);
IF (n.totalamount > 10000) THEN
SET emplname =(SELECT lname FROM emp WHERE empid=n.empno);
INSERT INTO travel_audit
VALUES(n.empno,emplname,n.deptno,n.totalamount,n.enddate);
END IF;
END

12 © 2017 IBM Corporation


M
IB

6
1/14/2017

IBM Power Systems

A Common Language

13 © 2017 IBM Corporation

IBM Power Systems

SQL Compound Statement


NOT ATOMIC
BEGIN
ATOMIC
<declare variables>
Compound <declare conditions> Declarations
Statement <declare cursors>
<declare handlers>
Logic -
<program logic > Can contain nested
compound statements

END

 ATOMIC
– All statements succeed or are rolled back
– COMMIT or ROLLBACK cannot be specified in the routine
– Must also be created with COMMIT ON RETURN YES

 NOT ATOMIC – no guarantee of atomicity

14 © 2017 IBM Corporation


M
IB

7
1/14/2017

IBM Power Systems

Basic Constructs
 DECLARE – define variable. Initialized when procedure is called
DECLARE v_midinit, v_edlevel CHAR(1);
DECLARE v_ordQuantity INT DEFAULT 0;
DECLARE v_enddate DATE DEFAULT NULL;
– Uninitialized variables set to NULL
– Single-dimension arrays
CREATE TYPE pids AS CHAR(3) ARRAY[ ];
CREATE TYPE intarray AS INTEGER ARRAY[5];

 SET - assigning a variable or parameter


SET total_salary = emp_salary + emp_commission;
SET total_salary = NULL;
SET loc_avgsalary = (SELECT AVG(salary) FROM employees);

 Comments - two types


– -- Two consecutive hyphens, rest of line is a comment
– /*… */ Bracketed comments, within brackets is a comment

15 © 2017 IBM Corporation

IBM Power Systems

Conditional Constructs
 IF statement
IF rating=1 THEN SET price=price * 0.95;
ELSEIF rating=2 THEN SET price=price * 0.90;
ELSE SET price=price * 0.80;
END IF;

 CASE Expression
– First form: – Second form:

CASE workdept CASE


WHEN 'A00' THEN WHEN vardept='A00' THEN
UPDATE department UPDATE department
SET deptname = 'ACCOUNTING'; SET deptname = 'ACCOUNTING';
WHEN 'B01' THEN WHEN vardept='B01' THEN
UPDATE department UPDATE department
SET deptname = 'SHIPPING'; SET deptname = 'SHIPPING';
… …
ELSE UPDATE department ELSE UPDATE department
SET deptname = 'UNKNOWN’; SET deptname = 'UNKNOWN';
END CASE;
END CASE;

16 © 2017 IBM Corporation


M
IB

8
1/14/2017

IBM Power Systems

Looping Constructs
 FOR statement - execute a statement for each row of a query

Ex:
FOR loopvar AS
loopcursor CURSOR FOR
SELECT firstname, middinit, lastname FROM emptbl
DO
SET fullname=lastname||', ' || firstname||' ' || middinit;
INSERT INTO namestbl VALUES( fullname );
END FOR;

 Allows columns in SELECT statement to be accessed directly!


 Cursor can be used in WHERE CURRENT OF... operation

17 © 2017 IBM Corporation

IBM Power Systems

Looping Constructs
 LOOP, REPEAT and WHILE statements
LOOP Example - REPEAT Example -
fetch_loop: r_loop:
LOOP REPEAT
FETCH cursor1 INTO FETCH cursor1 INTO
v_firstname, v_lastname; v_firstname, v_lastname;
IF SQLCODE <> 0 THEN …
LEAVE fetch_loop; UNTIL SQLCODE <> 0
END IF; END REPEAT;

END LOOP;

WHILE Example -
while_loop:
WHILE at_end=0 DO
NOTE: Though they look similar,
FETCH cursor1 INTO each example works differently!
v_firstname, v_lastname;
IF SQLCODE <> 0 THEN
SET at_end = 1;
END IF;

END WHILE;
18 © 2017 IBM Corporation
M
IB

9
1/14/2017

IBM Power Systems

Default Parameters

 Both Procedures and Functions (as of v7r2) support default


parameters
– Parameters can be omitted from invocation when a default value is
defined
– Parameters may also be specified in any order by specifying the
parameter name in the call

CREATE FUNCTION New_Prescription (


drugName CHAR(40),
prescID INTEGER DEFAULT (VALUES(NEXT VALUE FOR idSequence)),
refills INTEGER DEFAULT 0) ...

Omitting parameters – defaults Using a named parameter


used
New_Prescription(‘Accutane') New_Prescription(‘Accutane',
refills=>3)
19 © 2017 IBM Corporation

IBM Power Systems

SET options
SQL routine body
SET OPTION stmts

 SET OPTION - set processing options


– Naming option (*SQL vs *SYS), sort-sequence, SQL path, debug…
– Example:
SET DBGVIEW=*STMT, USRPRF=*USER

 Most interesting options for SQL Routines are:


– USRPRF for adopted authority (defaults to *OWNER)
– DBGVIEW for creating debuggable version of SQL Procedure
• *SOURCE enables SQL statement-level debug

20 © 2017 IBM Corporation


M
IB

10
1/14/2017

IBM Power Systems

Error Handling
and
Feedback

21 © 2017 IBM Corporation

IBM Power Systems

Feedback and Error Handling

Routines provide a rich set of error and message handling capabilites

 GET DIAGNOSTICS
 SQLSTATE and SQLCODE variables
 CONDITIONs and HANDLERs
 SIGNAL and RESIGNAL
 RETURN statement

22 © 2017 IBM Corporation


M
IB

11
1/14/2017

IBM Power Systems

Feedback & Error Handling

 GET DIAGNOSTICS
– Retrieve information about last statement executed
• Row_count, return_status, error status….
– CURRENT or STACKED
• CURRENT – statement that was just executed
• STACKED – statement before error handler was entered
– Only allowed within error handler
– Example:
DECLARE update_counter INTEGER;
...
UPDATE orders SET status=‘LATE’
WHERE ship_date < CURRENT DATE;
GET DIAGNOSTICS update_counter = ROW_COUNT;
...

23 © 2017 IBM Corporation

IBM Power Systems

Feedback & Error Handling

 CONDITION
DECLARE condition name CONDITION FOR string constant;
– Allows alias for cryptic SQLSTATE
– Condition name must be unique within the Stored Procedure

 HANDLER
DECLARE type HANDLER FOR condition;
– Type
•UNDO - rollback statements in compound statement (must be ATOMIC)
•CONTINUE – continue processing
•EXIT – exit compound statement
– Condition
•Defined condition (above)
•SQLSTATE ‘xxyzz’
• predefined: SQLWARNING, NOT FOUND, SQLEXCEPTION

24 © 2017 IBM Corporation


M
IB

12
1/14/2017

IBM Power Systems

Feedback & Error Handling Example


CREATE PROCEDURE proc1()

BEGIN
DECLARE at_end CHAR(1) DEFAULT ‘N’;
-- row not found condition
DECLARE row_not_fnd CONDITION FOR '02000';
DECLARE CONTINUE HANDLER FOR row_not_fnd
SET at_end='Y'; -- set local variable at_end

DELETE FROM tablex WHERE hiredate < ‘01/01/1990';

END

25 © 2017 IBM Corporation

IBM Power Systems

Feedback & Error Handling


 SIGNAL & RESIGNAL should be used to pass back error or
status to the invoker
– SIGNAL: SIGNAL condition info SET assign value;
•Condition info – condition name or SQLSTATE ‘xxyzz’
•SET clause provides ability to pass along additional diagnostic info
– MESSGE_TEXT most commonly used
– Values that can be retrieved via GET DIAGNOSTICS

– RESIGNAL: RESIGNAL [condition info SET assign value];


•Can be used only within handler
•Can just RESIGNAL – “bracket” info is optional
•Condition info – condition name or SQLSTATE ‘xxyzz’
•SET clause provides ability to pass along additional diagnostic info

– SIGNAL/RESIGNAL information is copied back to the SQLCA of the stored


procedure invoker
•EXAMPLE: VB program could retrieve the SQLSTATE and message text via the Connection
object (Conn.Error(i).SQLSTATE & Conn.Error(i).Description)

26 © 2017 IBM Corporation


M
IB

13
1/14/2017

IBM Power Systems

Signal & Resignal Example


CREATE PROCEDURE Change_Salary(IN i_empno CHAR(6),
IN i_change DEC(9,2) )
SPECIFIC CHGSAL LANGUAGE SQL
BEGIN

DECLARE EXIT HANDLER FOR SQLSTATE '38S01'


RESIGNAL SQLSTATE '38S01'
SET MESSAGE_TEXT ='CHGSAL: Change exceeds limit.';

DECLARE EXIT HANDLER FOR SQLSTATE '02000'


SIGNAL SQLSTATE '38S02'
SET MESSAGE_TEXT='CHGSAL: Invalid employee nbr.';

-- check, if the new compensation within the limit


IF (i_change > 25000) THEN
SIGNAL SQLSTATE '38S01';
END IF;

UPDATE employee SET salary=v_salary + i_salary WHERE empno = i_empno;

END

27 © 2017 IBM Corporation

IBM Power Systems

Feedback & Error Handling


 RETURN statement can be used to communicate high-level
success/failure status to caller
– RETURN <optional integer value>;
– If no return statement specified:
• If SQLCODE >= 0, then return value set to a value of 0
• If SQLCODE < 0, then return value set to -1
 Accessing the return value
– when invoked by another procedure
GET DIAGNOSTICS statusvar = RETURN_STATUS;
– "?=CALL <procedure name>" syntax common in ODBC and JDBC
– Returned in SQLERRD[0]

CREATE PROCEDURE ModAgency(IN agencyVID INTEGER,


IN agencyNUM INTEGER, IN agencyID INTEGER, IN agentNID INTEGER)
...
BEGIN
...
SUCCESS: RETURN 0;
INS_FAILURE: RETURN 900;
UPD_FAILURE: RETURN 901;
END;
28 © 2017 IBM Corporation
M
IB

14
1/14/2017

IBM Power Systems

Mixing Static and Dynamic SQL

It is possible, and quite common, to mix Static SQL and Dynamic SQL in
the same procedure (or Function):

 Static – Things you know about during the procedure creation

 Dynamic – to handle things that can vary

29 © 2017 IBM Corporation

IBM Power Systems

Static and Dynamic mix example


CREATE OR REPLACE PROCEDURE Process_Table
(DATALIB VARCHAR(128), DATATABLE VARCHAR(128))
LANGUAGE SQL
MODIFIES SQL DATA
SET OPTION COMMIT = *NC

BEGIN
DECLARE NF INT DEFAULT 0;
DECLARE EOF INT DEFAULT 0;
DECLARE D_SQL VARCHAR(3000);
DECLARE D_ITEM_KEY CHAR(8);
DECLARE NOTFOUND CONDITION FOR '42704';
DECLARE CONTINUE HANDLER FOR NOTFOUND SET NF = 1;
DECLARE CONTINUE HANDLER FOR SQLSTATE '02000‘ SET EOF = 1;

SET D_SQL = 'SELECT ITEM_KEY FROM ‘ CONCAT DATALIB CONCAT ‘.’ CONCAT DATATABLE;
PREPARE ITEM_P FROM D_SQL;

BEGIN
DECLARE ITEM_CURSOR CURSOR FOR ITEM_P;
OPEN ITEM_CURSOR;
IF NF=1 THEN
...
RETURN;
END IF;
FETCH ITEM_CURSOR INTO D_ITEM_KEY;
FETCHLOOP: WHILE EOF=0
DO

END FETCHLOOP;
CLOSE ITEM_CURSOR;
END;
END;

30 © 2017 IBM Corporation


M
IB

15
1/14/2017

IBM Power Systems

Routine Signatures

31 © 2017 IBM Corporation

IBM Power Systems

Create Procedure options


CREATE OR REPLACE PROCEDURE procedure name

( , )
IN
data type
OUT parm name
INOUT

 Procedure name + number of parameters make a unique signature


– Can have multiple procedures with the same name within a library
• NOTE: SPECIFIC names must be unique

Note: default parameters support in v7r1+ and V7R2 makes this less heavy handed

32 © 2017 IBM Corporation


M
IB

16
1/14/2017

IBM Power Systems

Create Function options


CREATE OR REPLACE FUNCTION function name

( , )

data type
parm name

 Function name + number of parameters + parameter (family) data type


make a unique signature
– Enables overloading / polymorphism for functions within the same library
Ex. These two functions are allowed in the same library (mylib):
mylib.func1(parm1 int)
mylib.func1(parm1 char)

Note: casting rules have changed (softened) as of v7r2

33 © 2017 IBM Corporation

IBM Power Systems

Stored Procedure
Result Sets

34 © 2017 IBM Corporation


M
IB

17
1/14/2017

IBM Power Systems

Result Sets & Procedures

 Procedures can return answer sets using result sets


 Returned result sets can be consumed by:
– System i Access ODBC, OLE DB & ADO.NET middleware
– SQL CLI
– Toolbox JDBC driver
– Native JDBC driver
– DB2 Connect
– IBM i DRDA Connections
– Embedded SQL & SQL Routines
– RPG, COBOL, C!
 Result sets are returned via open SQL cursors

35 © 2017 IBM Corporation

IBM Power Systems

SQL Procedures - Result Sets


CREATE PROCEDURE RegionCustList ( IN Region# INTEGER )
RESULT SET 1
LANGUAGE SQL

BEGIN
--Take the inputted region number, Region# and
--return the set of customers from that region
--via a result set

DECLARE c1 CURSOR WITH RETURN TO CALLER FOR


SELECT custnum, firstname,lastname
FROM custtable WHERE region = Region#;

OPEN c1;

END;

** Proprietary statement SET RESULT SETS CURSOR xx also supported

36 © 2017 IBM Corporation


M
IB

18
1/14/2017

IBM Power Systems

Result Set Considerations


Result Set Consumer Control
 RETURN TO CLIENT
Ex: DECLARE c1 CURSOR WITH RETURN TO CLIENT FOR SELECT * FROM t1

 RETURN TO CALLER
Ex: DECLARE c1 CURSOR WITH RETURN TO CALLER FOR SELECT * FROM t1

Proc 1 Proc 1

. .
. RETURN .

RETURN . .

Proc n-1
TO
TO Proc n-1
CALLER
CLIENT
Proc n Proc n

37 © 2017 IBM Corporation

IBM Power Systems

Result Set Consumption: Embedded SQL & SQL Routines


 Directly retrieve result sets with embedded SQL & SQL
Routines
– ASSOCIATE LOCATOR & ALLOCATE CURSOR statements


DECLARE sprs1 RESULT_SET_LOCATOR VARYING;
CALL GetProjs(projdept);
ASSOCIATE LOCATOR (sprs1) WITH PROCEDURE GetProjs;
ALLOCATE mycur CURSOR FOR RESULT SET sprs1;
SET totstaff=0;
myloop: LOOP
FETCH mycur INTO prname, prstaff;
Easy
IF row_not_found=1 THEN
Integration!
LEAVE fetch_loop;
END IF;
SET totstaff= totstaff + prstaff;
IF prstaff > moststaff THEN
SET bigproj = prname; ** DESCRIBE PROCEDURE &
SET moststaff= prstaff; DESCRIBE CURSOR statements
can be used to dynamically
END IF;
determine the number and
END LOOP;
contents of a result set
CLOSE mycur;

38 © 2017 IBM Corporation
M
IB

19
1/14/2017

IBM Power Systems

Programming considerations

39 © 2017 IBM Corporation

IBM Power Systems

SQL Routines - Compound Statement


 Compound statements can be executed as standalone dynamic SQL
requests within SQL scripts
- Conditional logic and error handling
- Input values with global variables

BEGIN
DECLARE CONTINUE HANDLER FOR SQLSTATE '42704'
BEGIN /* Table may or may not already exist*/
INSERT INTO error_log
VALUES(SESSION_USER, CURRENT TIMESTAMP, '42704');
END;

IF SESSION_USER <> ' DBADMIN' THEN


SIGNAL SQLSTATE '38001' SET MESSAGE_TEXT='Unauthorized User';
END IF;

IF Setuplib.Create_Var='YES' THEN
DROP TABLE orders;
CREATE TABLE orders(ordID CHAR(6), ordQty INTEGER, ordCustID CHAR(5));
END IF;
END;
40 © 2017 IBM Corporation
M
IB

20
1/14/2017

IBM Power Systems

Resolution of Procedure Calls


 Resolution of unqualified procedure and function invocations uses
SQL Path
– Default path values:
• System Naming: *LIBL
• SQL Naming: QSYS, QSYS2, SYSPROC, SYSIBMADM, authorization-ID
– Changing default schema with SET CURRENT SCHEMA has NO impact on
SQL Path
– SQL Path hard-coded at creation time for Procedure & Function calls on
embedded Static SQL statements

 Procedures & Functions support overloading which further complicates


resolution of unqualified invocations
– Enables multiple versions of a procedure & function can have the same name
within a schema

41 © 2017 IBM Corporation

IBM Power Systems

Protecting Source Code

 Source code for SQL procedural objects automatically stored in DB2


source code
– Some algorithms considered intellectual asset
– Customers can easily access intellectual asset:
SELECT routine_definition FROM qsys2/sysroutines
WHERE routine_name = ‘MY_ROUTINE’

 Obfuscation can be used to mask source code for protection. Two


methods available:
– WRAP Function – generate obfuscated version of CREATE statement
– CREATE_WRAPPED Procedure – creates obfuscated version of
procedure/function

42 © 2017 IBM Corporation


M
IB

21
1/14/2017

IBM Power Systems

WRAP Obfuscation Function


 Returns obfuscated version of SQL CREATE statement that can be run
on client’s system
– Returns obfuscated statement as CLOB value
– During product installation obfuscated statement executed to protect source
code stored in catalog

VALUES( SYSIBMADM.WRAP
(‘CREATE PROCEDURE chgSalary(IN empno CHAR(6))
LANGUAGE SQL BEGIN
UPDATE employee SET empsal = empsal*(1 + .05*empjobtype)
WHERE empid = empno; END’) );

CREATE PROCEDURE chgSalary ( IN EMPNO CHAR (6)) WRAPPED


QSQ07010
aacxW8plW8FjG8pnG8VzG8FD68Fj68:Hl8:dY_pB2qpdW8pdW8pdW_praqe
baqebaGEMj_vsPBs5bOJUUqnHVayEl_ogAlGWqz2jJCIE1dQEjt33hd5Sps5
cYGViD1urv7vGKeOcC4CwpCibb

43 © 2017 IBM Corporation

IBM Power Systems

CREATE_WRAPPED Obfuscation Procedure

 Creates obfuscated version of procedure/function* to protect source code


stored in DB2 catalog
– COMMIT level other than *NONE may be required when calling
CREATE_WRAPPED procedures on some SQL interfaces

CALL SYSIBMADM.CREATE_WRAPPED (
‘ CREATE PROCEDURE chgSalary(IN empno CHAR(6))
LANGUAGE SQL
BEGIN
UPDATE employee SET empsal = empsal*(1 + .05*empjobtype)
WHERE empid = empno; END’);

* And triggers in v7.2


44 © 2017 IBM Corporation
M
IB

22
1/14/2017

IBM Power Systems

Tools Available For Debugging

 Graphical Debuggers
– IBM i Graphical Debugger
• Not just for SQL Routines, any IBM i program
• Part of IBM Toolbox for Java

– IBM Data Studio

– Graphical debug white paper: https://ibm.biz/Bdxpni

 STRDBG command

45 © 2017 IBM Corporation

IBM Power Systems

Run SQL Scripts Debugger Interface


 Powerful tool for debugging SQL routines

 Activate two ways


– Debugger option from Run menu pull-down
– Use Ctrl+D hotkey sequence

46 © 2017 IBM Corporation


M
IB

23
1/14/2017

IBM Power Systems

IBM i Graphical Debugger & SQL Routines


 Display, modify and monitor variables
 Set breakpoints
 Step buttons may need to be clicked multiple times
– Single SQL statement may be implemented with multiple lines of C
code
Step thru code or
easily set
breakpoints

Console allows
usage of EVAL
commands

Program variables
displayed on the fly

47 © 2017 IBM Corporation

IBM Power Systems

IBM i Debuggers – Enablement Steps


 Use SET OPTION clause to enable SQL source-level debug
SET OPTION DBGVIEW = *SOURCE

 Debuggers only support 10 character program names


– Use SPECIFIC clause to provide meaningful short name
CREATE PROCEDURE LONG_PROCEDURE_NAME ( )
SPECIFIC LONGPROC …

 Specify BEGIN label to enable EVAL command for local variables

CREATE PROCEDURE proc1(IN p1 INT)


LANGUAGE SQL SET OPTION DBGVIEW=*SOURCE
sp: BEGIN
DECLARE x INT;
SET x = p1 + 5;
END;

48 © 2017 IBM Corporation


M
IB

24
1/14/2017

IBM Power Systems

More Information

49 © 2017 IBM Corporation

IBM Power Systems

The Full Story

A refreshed (2016) procedure RedBook is available!

http://www.redbooks.ibm.com/redpieces/abstracts/sg248326.html

50 © 2017 IBM Corporation


M
IB

25
1/14/2017

IBM Power Systems

Additional Information
 DB2 for i Websites
– Homepage: www.ibm.com/systems/power/software/i
– Technology Updates
www.ibm.com/developerworks/ibmi/techupdates/db2
– developerWorks Zone: www.ibm.com/developerworks/data/products.html

 Forums
– developerWorks:
https://ibm.com/developerworks/forums/forum.jspa?forumID=292

 Articles on procedure resolution related to default parameters


– http://www.ibm.com/developerworks/ibmi/library/i-sqlnaming/index.html
– http://www.ibm.com/developerworks/ibmi/library/i-system_sql2/index.html

51 © 2017 IBM Corporation

IBM Power Systems

DB2 for IBM i Lab Services


• Facilitated workshops covering current state, requirements, future state,
possible solutions, implementation best practices, and formulation of a
strategic roadmap:

• RCAC

• Temporal Tables

• Customized consulting workshops

• Advanced SQL and Datacentric Programming

• SQL Performance Best Practices, Monitoring and Tuning

• Consulting on any DB2 for i topic

For more information, contact [email protected]

52 © 2017 IBM Corporation


M
IB

26
1/14/2017

IBM Power Systems

Thank you!

53 © 2017 IBM Corporation

IBM Power Systems

Trademarks and Disclaimers


Adobe, Acrobat, PostScript and all Adobe-based trademarks are either registered trademarks or trademarks of Adobe Systems Incorporated in the United States, other
countries, or both.
Intel, Intel logo, Intel Inside, Intel Inside logo, Intel Centrino, Intel Centrino logo, Celeron, Intel Xeon, Intel SpeedStep, Itanium, and Pentium are trademarks or registered
trademarks of Intel Corporation or its subsidiaries in the United States and other countries.
Linux is a registered trademark of Linus Torvalds in the United States, other countries, or both.
Microsoft, Windows, Windows NT, and the Windows logo are trademarks of Microsoft Corporation in the United States, other countries, or both.
IT Infrastructure Library is a registered trademark of the Central Computer and Telecommunications Agency which is now part of the Office of Government Commerce.
ITIL is a registered trademark, and a registered community trademark of the Office of Government Commerce, and is registered in the U.S. Patent and Trademark Office.
UNIX is a registered trademark of The Open Group in the United States and other countries.
Cell Broadband Engine and Cell/B.E. are trademarks of Sony Computer Entertainment, Inc., in the United States, other countries, or both and are used under license
therefrom.
Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. in the United States, other countries, or both.
Other company, product, or service names may be trademarks or service marks of others.
Information is provided "AS IS" without warranty of any kind.
The 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.
Information concerning non-IBM products was obtained from a supplier of these products, published announcement material, or other publicly available sources and does
not constitute an endorsement of such products by IBM. Sources for non-IBM list prices and performance numbers are taken from publicly available information,
including vendor announcements and vendor worldwide homepages. IBM has not tested these products and cannot confirm the accuracy of performance, capability, or
any other claims related to non-IBM products. Questions on the capability of non-IBM products should be addressed to the supplier of those products.
All statements regarding IBM future direction and intent are subject to change or withdrawal without notice, and represent goals and objectives only.
Some information addresses anticipated future capabilities. Such information is not intended as a definitive statement of a commitment to specific levels of performance,
function or delivery schedules with respect to any future products. Such commitments are only made in IBM product announcements. The information is presented here
to communicate IBM's current investment and development activities as a good faith effort to help with our customers' future planning.
Performance is based on measurements and projections using standard IBM benchmarks in a controlled environment. The actual throughput or performance that any
user will experience will vary depending upon considerations such as the amount of multiprogramming in the user's job stream, the I/O configuration, the storage
configuration, and the workload processed. Therefore, no assurance can be given that an individual user will achieve throughput or performance improvements
equivalent to the ratios stated here.
Prices are suggested U.S. list prices and are subject to change without notice. Contact your IBM representative or Business Partner for the most current pricing in your
geography.

54 © 2017 IBM Corporation


M
IB

27

You might also like