Sie sind auf Seite 1von 22

IBM DB2 for i Center of Excellence

DB2 for i

IBM DB2 for i Technical Forun - Lima, Peru - May 2016


SQL Stored Procedures

2014 IBM Corporation

Procedural SQL

SQL Routines Overview


Advanced SQL Stored Procedure Techniques
Resolution of Procedure & Function Calls
Source Code Protection for SQL Routines

2014 IBM Corporation


Procedural SQL

SQL Routines Overview

IBM DB2 for i Technical Forun - Lima, Peru - May 2016


Advanced SQL Stored Procedure Techniques
Resolution of Procedure & Function Calls
Source Code Protection for SQL Routines

2014 IBM Corporation

Introduction to SQL Routines

SQL is also a programming language!

SQL Routines (Procedures, Triggers, Functions) created with


SQL procedural programming language
Enhances portability
Supported across DB2 Family DB2 implementation follows
SQL PSM Standard
Similar to proprietary procedure languages available from other
DBMS (PL/SQL, T-SQL, etc)
First introduced at V4R2

Makes it easier for SQL programmers to be productive


faster on IBM i

4 2014 IBM Corporation


Introduction to SQL Routines
Comparison of SQL Routine types
Stored Procedures

IBM DB2 for i Technical Forun - Lima, Peru - May 2016


Similar to high-level language program, facilitate reuse of common
business logic or business process
Most commonly used to call procedure on another system
Minimize network traffic
Secure data access
Invoked with SQL CALL statement by developer
Triggers
Mechanism to guarantee that same business process occurs on every
data change operation regardless of interface
Invoked by DB2
User-Defined Function
Most commonly called for each row being processed during SQL
statement execution
Invoked from SQL statement by developer
SELECT myfunc1() FROM mytable WHERE myfunc2(col1)>100

5 2014 IBM Corporation

Introduction to SQL Routines

Each time that an SQL Routine is created, DB2 for i uses the SQL
procedural source to generate a C program object
Developer does not need to know C code
C compiler purchase is not required

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 2014 IBM Corporation
SQL Routine - Create Options

CREATE OR REPLACE routine name

IBM DB2 for i Technical Forun - Lima, Peru - May 2016


LANGUAGE SPECIFIC specific name PROGRAM TYPE

SQL MAIN
RPGLE
SUB

OR REPLACE New 7.1 Feature, similar to REPLACE(*YES)


LANGUAGE - Language of procedure (SQL, C, RPG)
SPECIFIC unique "short" name for SQL procedures & UDFs
Automatically generated if not specified
Can be used to control C program object name
PROGRAM NAME clause available for SQL Triggers

PROGRAM TYPE SUB enables DB2 to create service program object


for a procedure for better performance
SQL Functions always implemented with service program object
SQL Triggers always implemented with program object

7 2014 IBM Corporation

SQL Routine - Create Options

MODIFIES SQL DATA

NO SQL
READS SQL DATA
CONTAINS SQL

MODIFIES SQL DATA Most any SQL statement allowed


READS SQL DATA Read Only statements
CONTAINS SQL Simple local statements (SET, DECLARE)
NO SQL No SQL allowed (external procedures only)

* Not Applicable to Triggers

8 2014 IBM Corporation


SQL Routines - Create Options

SQL routine body

IBM DB2 for i Technical Forun - Lima, Peru - May 2016


SET OPTION clause

SET OPTION - set processing options


Naming option (*SQL vs *SYS), sort-sequence, SQL path, debug
Example: SET DBGVIEW=*SOURCE, 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

9 2014 IBM Corporation

SQL Routines - Compound Statement

NOT ATOMIC
BEGIN
ATOMIC
<declare variables>
Compound <declare conditions> Declarations
Statement <declare cursors>
<declare handlers>
Logic -
<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 or atomicity


10 2014 IBM Corporation
SQL Routines - Basic Constructs
DECLARE define variable. Initialized when procedure is called
DECLARE v_midinit, v_edlevel CHAR(1);

IBM DB2 for i Technical Forun - Lima, Peru - May 2016


DECLARE v_ordQuantity INT DEFAULT 0;
DECLARE v_enddate DATE DEFAULT NULL;

Uninitialized variables set to NULL


Single-dimension arrays supported in 7.1 release
CREATE TYPE pids AS CHAR(3) ARRAY[ ];
CREATE TYPE intarray AS INTEGER ARRAY[5];
SET - assigning a value parameter or variable
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 (--)
Bracketed comments (/* ... */)

11 2014 IBM Corporation

SQL Routines - Basic Constructs

CALL statement - for invoking stored procedures

CALL ProcedureName(Parm1,Parm2, etc);


Up to 1024 arguments allowed on CALL statement
A parameter can contain SQL parameter, SQL variable,
constant, special register, or NULL
Expressions supported as parameters in 7.1 release

Provides a mechanism for accessing system functions and


APIs from an SQL Stored Procedure

12 2014 IBM Corporation


SQL Routines - Conditional Constructs
IF statement
IF rating=1 THEN SET price=price * 0.95;

IBM DB2 for i Technical Forun - Lima, Peru - May 2016


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;

13 2014 IBM Corporation

SQL Routines - Looping Constructs


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
FETCH cursor1 INTO
v_firstname, v_lastname;
IF SQLCODE <> 0 THEN
SET at_end = 1;
END IF; NOTE: Though they look similar,
each example works differently!
END WHILE;
14 2014 IBM Corporation
SQL Routines - Looping Constructs

FOR statement - execute a statement for each row of a table

IBM DB2 for i Technical Forun - Lima, Peru - May 2016


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 FOR SELECT statement to be accessed


directly without host variables
Cursor can be used in WHERE CURRENT OF... operation

15 2014 IBM Corporation

Procedural SQL

SQL Routines Overview


Advanced SQL Stored Procedure Techniques
Resolution of Procedure & Function Calls
Source Code Protection for SQL Routines

2014 IBM Corporation


Advanced SQL Stored Procedures

Default Parameters

IBM DB2 for i Technical Forun - Lima, Peru - May 2016


Arrays
Result Sets: Producing and Consuming

2014 IBM Corporation

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
schema

1024 is maximum number of parameters

2014 IBM Corporation


Create Procedure options

IBM DB2 for i Technical Forun - Lima, Peru - May 2016


DYNAMIC RESULT SETS 0

DYNAMIC RESULT SETS integer

RESULT SETS specifies max number of result sets that can


be returned from procedure.

Returned to ODBC, JDBC, .NET & CLI clients


Result sets returned to Embedded SQL clients in 7.1 release

2014 IBM Corporation

Parameter Defaults
DEFAULT
NULL
constant
special-register
global-register
( expression )

New support added in 7.1 to minimize code changes when


adding new parameters
Parameters may be omitted if the routine was defined with a default
value
Parameters may be specified in any order by specifying the
parameter name in the call
Supported for SQL & External stored procedures

2014 IBM Corporation


Parameter Defaults Examples

The following example is a procedure with 4 input columns


NAME is required

IBM DB2 for i Technical Forun - Lima, Peru - May 2016


If ID is omitted, then retrieve the next value from a sequence
If DEPT is omitted, then use the value 123
If DATE_HIRED is omitted then use the CURRENT DATE special register

CREATE PROCEDURE New_Hire (


name CHAR(40),
id INTEGER DEFAULT (VALUES(NEXT VALUE FROM EmployeeIDs)),
dept CHAR(3) DEFAULT 123
date_hired DEFAULT CURRENT DATE) ...

Omitting parameters defaults Using a named parameter


used
CALL New_Hire('John Doe') CALL New_Hire('John Doe',
Date_Hired=>'06/23/2012')

2014 IBM Corporation

ARRAY support for SQL Routines

Enables exchange of data collections


ARRAY element limited to simple data types
ARRAY type can be used as parameter for SQL Routine or a
local variable
Interfaces supporting SQL Routine ARRAY parameters:
JDBC
SQL Routines
Note: Host language arrays cannot be passed to ARRAY parameters

Examples:
CREATE TYPE partids AS CHAR(3) ARRAY[10];
CREATE TYPE intarray AS INTEGER ARRAY[5];

2014 IBM Corporation


ARRAY Example
Return part type and quantity for the specified collection of parts
CREATE PROCEDURE list_parts(IN inparts partids,

IBM DB2 for i Technical Forun - Lima, Peru - May 2016


OUT part_qty intarray)
DYNAMIC RESULT SETS 1 LANGUAGE SQL
BEGIN
DECLARE cur1 CURSOR FOR SELECT t.id,part_qty, part_type
FROM parts, UNNEST(inparts) AS t(id) WHERE t.id = part_id;
IF CARDINALITY( inparts )>5 THEN
SIGNAL SQLSTATE '38003' SET MESSAGE_TEXT='Too many parts';
END IF;
SET part_qty =
(SELECT ARRAY_AGG(part_qty)
FROM parts,UNNEST(inparts) AS t2(id)
WHERE t2.id = part_id);
OPEN cur1;
END;
OUTPUT
Invoker Code: out_qty Array:
SET myparts = ARRAY[W12,S55,M22]; [1] = 25
[2] = 124
CALL list_parts(myparts, out_qty);
[3] = 125
2014 IBM Corporation

Result Sets and Procedures

Stored procedures in combination with result sets can


drastically reduce network trips by returning blocks of results
Stored procedures that return result sets can only be called
by the following interfaces
System i Access ODBC, OLE DB & ADO.NET middleware
SQL CLI
Toolbox JDBC driver
Native JDBC driver
DB2 Connect
IBM i DRDA Connections
New with 7.1 - Embedded SQL & SQL Routines
Result sets are returned via open SQL cursors with SQL
procedures

2014 IBM Corporation


Result Set Example
CALL RegionCustList(16)

IBM DB2 for i Technical Forun - Lima, Peru - May 2016


2014 IBM Corporation

SQL Procedures - Result Sets (Standard)

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;

2014 IBM Corporation


SQL Procedures - Result Sets (Proprietary)

CREATE PROCEDURE RegionCustList ( IN Region# INTEGER )

IBM DB2 for i Technical Forun - Lima, Peru - May 2016


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 FOR


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

OPEN c1;

SET RESULT SETS CURSOR c1;


END;

2014 IBM Corporation

Result Set Considerations

Result Set Consumer Control


RETURN TO CLIENT
DECLARE c1 CURSOR WITH RETURN TO CLIENT FOR SELECT * FROM t1

SET RESULT SETS WITH RETURN TO CLIENT FOR CURSOR c1

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

SET RESULT SETS WITH RETURN TO CALLER FOR


ARRAY :array1 FOR :hv1 ROWS

Proc 1 Proc 1

. .
. RETURN .

RETURN . .
TO
TO Proc n-1 Proc n-1
CALLER
CLIENT
Proc n Proc n

2014 IBM Corporation


Embedded SQL Result Set Consumption Enablers

There are 3 statements required to consume a result set


created by a called stored procedure

IBM DB2 for i Technical Forun - Lima, Peru - May 2016


DECLARE RESULT_SET_LOCATOR VARYING
Defines a variable which contains the location of a result set

ASSOCIATE LOCATORS
Ties locator to stored procedure result set

ALLOCATE CURSOR
Defines cursor that can be used to access & process data in result
set
Once cursor allocated, program can use normal FETCH and
CLOSE operations

2014 IBM Corporation

Result Set Consumption Example: SQL Routine


DECLARE sprs1 RESULT_SET_LOCATOR VARYING;
CALL GetProjs(projdept);

ASSOCIATE LOCATOR (sprs1) WITH PROCEDURE GetProjs;


ALLOCATE mycur CURSOR FOR RESULT SET sprs1;

myloop: LOOP
FETCH mycur INTO prname, prstaff;

IF row_not_found=1 THEN LEAVE myloop; END IF;

SET totstaff= totstaff + prstaff;


END LOOP;

IF totstaff > deptstaff THEN


SET understaffed = totstaff - deptstaff;
END IF;
CLOSE mycur;

2014 IBM Corporation


Result Set Consumption Complete Example
Calling Procedure Result Set Procedure
DECLARE L1 RESULT_SET_LOCATOR VARYING; CREATE PROCEDURE GetProjs(iDep CHAR(3))

IBM DB2 for i Technical Forun - Lima, Peru - May 2016


CALL GetProjs(projdept); RESULT SETS 1
LANGUAGE SQL
BEGIN
ASSOCIATE LOCATOR(L1) WITH PROCEDURE DECLARE cursor1 CURSOR WITH RETURN
GetProjs; FOR SELECT Projname, Prstaff
ALLOCATE mycur CURSOR FOR RESULT SET L1; FROM project
WHERE deptno = iDep
myloop: LOOP ORDER BY Projname;
FETCH mycur INTO prname, prstaff;
OPEN cursor1;
IF row_not_found=1 THEN LEAVE myloop;
END;
END IF;
SET totstaff= totstaff + prstaff;
END LOOP;

IF totstaff > deptstaff THEN


SET understaffed = totstaff - deptstaff;
END IF;

2014 IBM Corporation

Result Set Consumption: Embedded SQL

Invoking RPG SQL Program


D RS_LOC1 S
SQLTYPE(RESULT_SET_LOCATOR)
EXEC SQL CALL RS1_PROC(E11); Result Set Procedure
EXEC SQL ASSOCIATE RESULT SET CREATE PROCEDURE RS1_PROC (
IN iDep CHAR(3))
LOCATORS (:RS_Loc1)WITH RESULT SETS 1
PROCEDURE RS1_PROC; LANGUAGE SQL
BEGIN
EXEC SQL ALLOCATE C1 CURSOR FOR
DECLARE RS1_PROC_C1 CURSOR FOR
RESULT SET :RS_Loc1; SELECT * FROM VEMPDPT3
WHERE WORKDEPT = iDep;
EXEC SQL FETCH NEXT FROM C1 FOR n
ROWS INTO:RS_Array; OPEN RS1_PROC_C1;
END;

2014 IBM Corporation


Procedural SQL

SQL Routines Overview

IBM DB2 for i Technical Forun - Lima, Peru - May 2016


Advanced SQL Stored Procedure Techniques
Resolution of Procedure Calls
Source Code Protection for SQL Routines

2014 IBM Corporation

Resolution of Procedure Calls


Resolution of unqualified procedure and function invocations
works differently than other DB2 objects (tables, views ,etc)
SQL Path used to find the schema for function or schema
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 Static SQL statements embedded within

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
Also known as polymorphism

2014 IBM Corporation


Resolution of Procedure Calls
Stored Procedure signature determined by the procedure
name and number of parameters

IBM DB2 for i Technical Forun - Lima, Peru - May 2016


These two procedures have unique signatures, so they can reside
within the same schema
CREATE PROCEDURE myproc(IN i1 INT)
CREATE PROCEDURE myproc(IN i1 INT, IN i2 INT)
These procedures have duplicate signatures, so they cannot reside
within the same schema
CREATE PROCEDURE myproc(IN i1 INT, IN i3 CHAR(3))
CREATE PROCEDURE myproc(IN i1 INT, IN i2 INT)

Overloaded Procedure (& Function) cleanup


Use specific name on DROP statement
OR Include signature in DROP statement
DROP PROCEDURE myproc(INT)

2014 IBM Corporation

Resolution of Procedure Calls


Example assume following DB2 objects have been created
CREATE PROCEDURE s1.myproc(IN i1 INT)
CREATE TABLE s1.t1 (c1 INT);
CREATE PROCEDURE s1.myproc(IN i1 INT, IN i2 INT)
CREATE PROCEDURE s2.myproc(IN i1 INT, IN i3 INT)
CREATE PROCEDURE s2.myproc(IN i1 INT)
CREATE TABLE s2.t1 (c1 INT);

Dynamic SQL used to execute the following SQL statements,


which object is used by DB2?
SET PATH = SYSPROC, S1;
SET SCHEMA = S2;
CALL myproc(33);
SELECT * FROM t1;
CALL myproc(11,33);
CALL myproc(11,CURRENT DATE);

2014 IBM Corporation


Resolution of Procedure Calls
Stored Procedure output parameter support in Run SQL
Scripts

IBM DB2 for i Technical Forun - Lima, Peru - May 2016


CREATE PROCEDURE proc1(IN p1 INT, OUT p2 INT)

CALL proc1 (100, ?)

Resources
DB2 for i SQL Reference - http:ibm.com/systems/i/db2/books.html

IBM i developerWorks articles:

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

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

2014 IBM Corporation

Procedural SQL

SQL Routines Overview


Advanced SQL Stored Procedure Techniques
Resolution of Procedure Calls
Source Code Protection for SQL Routines

2014 IBM Corporation


Protecting Procedure & Function Source Code

Source code for SQL procedural objects automatically stored

IBM DB2 for i Technical Forun - Lima, Peru - May 2016


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

2014 IBM Corporation

WRAP Obfuscation Function

Returns obfuscated version of SQL CREATE statement that


can be run on clients 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

2014 IBM Corporation


CREATE_WRAPPED Obfuscation Procedure

Creates obfuscated version of procedure/function to protect

IBM DB2 for i Technical Forun - Lima, Peru - May 2016


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);

2014 IBM Corporation

Obfuscation Considerations
Obfuscated version of CREATE statement can be up to
one-third longer than original SQL statement

Obfuscation provides protection, but its not a strong form of


encryption

Obfuscated routines cannot be debugged


Clients would need to be provided with a debuggable version to use
temporarily

Obfuscation is preserved if associated program object is


saved and restored onto another system

Obfuscation for SQL triggers being worked on for a future


release
2014 IBM Corporation
2014 IBM Corporation

IBM DB2 for i Technical Forun - Lima, Peru - May 2016

Das könnte Ihnen auch gefallen