® IBM Software Group © IBM Corporation QUY Thai Duy – ITFac DLU [email protected],...

33
® IBM Software Group © IBM Corporation QUY Thai Duy – ITFac DLU [email protected], [email protected] Lesson 12: SQL PL Stored Procedures

Transcript of ® IBM Software Group © IBM Corporation QUY Thai Duy – ITFac DLU [email protected],...

Page 1: ® IBM Software Group © IBM Corporation QUY Thai Duy – ITFac DLU quytd@dlu.edu.vn, thaiduyquy@gmail.com Lesson 12: SQL PL Stored Procedures.

®

IBM Software Group

© IBM Corporation

QUY Thai Duy – ITFac [email protected], [email protected]

Lesson 12: SQL PL Stored Procedures

Page 2: ® IBM Software Group © IBM Corporation QUY Thai Duy – ITFac DLU quytd@dlu.edu.vn, thaiduyquy@gmail.com Lesson 12: SQL PL Stored Procedures.

IBM Software Group

Agenda

Stored procedures overview

IBM Data Studio

SQL PL Stored Procedures basicsCursors

Errors & condition handlers

Flow control

Calling Stored Procedures

User Define Function.

Trigger.

Page 3: ® IBM Software Group © IBM Corporation QUY Thai Duy – ITFac DLU quytd@dlu.edu.vn, thaiduyquy@gmail.com Lesson 12: SQL PL Stored Procedures.

IBM Software Group

Stored Procedures

Page 4: ® IBM Software Group © IBM Corporation QUY Thai Duy – ITFac DLU quytd@dlu.edu.vn, thaiduyquy@gmail.com Lesson 12: SQL PL Stored Procedures.

IBM Software Group

IBM Data Studio Replaces the DB2 Developer Workbench of DB2 9

Installed separately from DB2 9.5

Based on Eclipse

Powerful IDE that allows you to:

Create, edit, debug, deploy, test Java/SQL Stores Procedures, UDFs

Develop SQLJ applications

Create, alter, and drop DB2 database objects (with impact analysis)

Explore and edit data - relational and XML

Visually build SQL and and XQuery statements

Optimize queries using Visual Explain

Develop queries and routines for pureXML applications

Perform data movement tasks

Collaborate and share projects with team members

Quickly build SOAP and REST Web Services

Discover database object relationships with physical data models (diagraming)

Visualize data distribution across tables

Page 5: ® IBM Software Group © IBM Corporation QUY Thai Duy – ITFac DLU quytd@dlu.edu.vn, thaiduyquy@gmail.com Lesson 12: SQL PL Stored Procedures.

IBM Software Group

Creating your first SQL PL Stored Procedure

Using the Command Editor:

connect to sample

create procedure p1 begin end

Using the IBM Data Studio

Page 6: ® IBM Software Group © IBM Corporation QUY Thai Duy – ITFac DLU quytd@dlu.edu.vn, thaiduyquy@gmail.com Lesson 12: SQL PL Stored Procedures.

IBM Software Group

Basic stored procedure structure

<statement> is a single statement, or a set of statements

grouped by BEGIN [ATOMIC] ... END

Page 7: ® IBM Software Group © IBM Corporation QUY Thai Duy – ITFac DLU quytd@dlu.edu.vn, thaiduyquy@gmail.com Lesson 12: SQL PL Stored Procedures.

IBM Software Group

Optional stored procedure attributes

LANGUAGE SQL

RESULT SETS <n> (required if returning result sets)

SPECIFIC my_unique_name can be same as procedure name

highly recommended for manageability:

GRANT EXECUTE ON SPECIFIC PROCEDURE ...

DROP SPECIFIC PROCEDURE ...

Page 8: ® IBM Software Group © IBM Corporation QUY Thai Duy – ITFac DLU quytd@dlu.edu.vn, thaiduyquy@gmail.com Lesson 12: SQL PL Stored Procedures.

IBM Software Group

Parameters

CREATE PROCEDURE proc(IN p1 INT, OUT p2 INT, INOUT p3 INT)

...

IN - Input parameter

OUT - Output parameter

INOUT - Input and Output parameter

All params must be provided in CALL statement

Page 9: ® IBM Software Group © IBM Corporation QUY Thai Duy – ITFac DLU quytd@dlu.edu.vn, thaiduyquy@gmail.com Lesson 12: SQL PL Stored Procedures.

IBM Software Group

Comments in SQL PL Stored Procedures

-- This is an SQL-style comment

/* This is a C-style coment */

(valid within SQL procedures )

Page 10: ® IBM Software Group © IBM Corporation QUY Thai Duy – ITFac DLU quytd@dlu.edu.vn, thaiduyquy@gmail.com Lesson 12: SQL PL Stored Procedures.

IBM Software Group

Compound statements

Page 11: ® IBM Software Group © IBM Corporation QUY Thai Duy – ITFac DLU quytd@dlu.edu.vn, thaiduyquy@gmail.com Lesson 12: SQL PL Stored Procedures.

IBM Software Group

Variable declarationDECLARE var_name <data type> [ DEFAULT value];

Note: Default value is NULL

Examples:

DECLARE temp1 SMALLINT DEFAULT 0;

DECLARE temp2 INTEGER DEFAULT 10;

DECLARE temp3 DECIMAL(10,2) DEFAULT 100.10;

DECLARE temp4 REAL DEFAULT 10.1;

DECLARE temp5 DOUBLE DEFAULT 10000.1001;

DECLARE temp6 BIGINT DEFAULT 10000;

DECLARE temp7 CHAR(10) DEFAULT 'yes';

DECLARE temp8 VARCHAR(10) DEFAULT 'hello';

DECLARE temp9 DATE DEFAULT '1998-12-25';

DECLARE temp10 TIME DEFAULT '1:50 PM';

DECLARE temp11 TIMESTAMP DEFAULT '2001-01-05-12.00.00';

DECLARE temp12 CLOB(2G);

DECLARE temp13 BLOB(2G);

Page 12: ® IBM Software Group © IBM Corporation QUY Thai Duy – ITFac DLU quytd@dlu.edu.vn, thaiduyquy@gmail.com Lesson 12: SQL PL Stored Procedures.

IBM Software Group

Assignment statements SET total = 100;

Same as VALUES(100) INTO total;

SET total = NULL; any variable can be set to NULL

SET total = (select sum(c1) from T1); Condition is raised if more than one row

SET first_val = (select c1 from T1 fetch first 1 row only)

fetch only the first row from a table

SET sch = CURRENT SCHEMA;

Page 13: ® IBM Software Group © IBM Corporation QUY Thai Duy – ITFac DLU quytd@dlu.edu.vn, thaiduyquy@gmail.com Lesson 12: SQL PL Stored Procedures.

IBM Software Group

Quicklab: Stored procedure with parameters

To call the procedure from the Command Editor: call P2 (3, 4, ?)

CREATE PROCEDURE P2 ( IN v_p1 INT, INOUT v_p2 INT,OUT v_p3 INT)

LANGUAGE SQLSPECIFIC myP2BEGIN-- my second SQL procedureSET v_p2 = v_p2 + v_p1;SET v_p3 = v_p1;END

Page 14: ® IBM Software Group © IBM Corporation QUY Thai Duy – ITFac DLU quytd@dlu.edu.vn, thaiduyquy@gmail.com Lesson 12: SQL PL Stored Procedures.

IBM Software Group

Cursors

cursor declaration and usage:

DECLARE <cursor name> CURSOR [WITH RETURN <return target>]

<SELECT statement>;

OPEN <cursor name>;

FETCH <cursor name> INTO <variables>

CLOSE <cursor name>;

result sets can also be directly returned to CLIENT or CALLER for processing CLIENT: result set will return to client application

CALLER: result set is returned to client or stored procedure that made the call

Page 15: ® IBM Software Group © IBM Corporation QUY Thai Duy – ITFac DLU quytd@dlu.edu.vn, thaiduyquy@gmail.com Lesson 12: SQL PL Stored Procedures.

IBM Software Group

Quicklab: Stored procedure returning result sets

CREATE PROCEDURE set ()

DYNAMIC RESULT SETS 1

LANGUAGE SQL

BEGIN

DECLARE cur CURSOR WITH RETURN TO CLIENT

FOR SELECT name, dept, job

FROM staff

WHERE salary > 20000;

OPEN cur;

END

Page 16: ® IBM Software Group © IBM Corporation QUY Thai Duy – ITFac DLU quytd@dlu.edu.vn, thaiduyquy@gmail.com Lesson 12: SQL PL Stored Procedures.

IBM Software Group

Flow control statements

CASE (selects an execution path (simple / searched))

IF

FOR (executes body for each row of table)

WHILE

ITERATE (forces next iteration. Similar to CONTINUE in C)

LEAVE (leaves a block or loop. "Structured Goto")

LOOP (infinite loop)

REPEAT

GOTO

RETURN

CALL (procedure call)

Page 17: ® IBM Software Group © IBM Corporation QUY Thai Duy – ITFac DLU quytd@dlu.edu.vn, thaiduyquy@gmail.com Lesson 12: SQL PL Stored Procedures.

IBM Software Group

Dynamic SQL

Useful when the final form of SQL is know only at RUN TIME

example: if col1 and tabname are variables:

'SELECT ' || col1 || ' FROM ' || tabname;

Also recommended for DDL to avoid dependency problems and package invalidation, and to implement recursion.

Keywords: EXECUTE IMMEDATE - ideal for single execution SQL

PREPARE + EXECUTE - ideal for multiple execution SQL

Page 18: ® IBM Software Group © IBM Corporation QUY Thai Duy – ITFac DLU quytd@dlu.edu.vn, thaiduyquy@gmail.com Lesson 12: SQL PL Stored Procedures.

IBM Software Group

Quicklab: Dynamic SQL

prerequisite: create table T2 (c1 int, c2 int)

CREATE PROCEDURE dyn1 (IN value1 INT, IN value2 INT)SPECIFIC dyn1BEGIN

DECLARE stmt varchar(255);DECLARE st STATEMENT;

SET stmt = 'insert into T2 values (?, ?)';

PREPARE st FROM stmt;

EXECUTE st USING value1, value1;EXECUTE st USING value2, value2;

SET stmt = 'insert into T2 values (9,9)';EXECUTE IMMEDIATE stmt;

END

Page 19: ® IBM Software Group © IBM Corporation QUY Thai Duy – ITFac DLU quytd@dlu.edu.vn, thaiduyquy@gmail.com Lesson 12: SQL PL Stored Procedures.

IBM Software Group

Calling Stored Procedures from a Java ApplicationTry {

// Connect to sample database

String url = “jdbc:db2:sample”;

con = DriverManager.getConnection(url);

CallableStatement cs = con.prepareCall(“CALL trunc_demo(?, ?)”);

// register the output parameters

callStmt.registerOutParameter(1, Types.VARCHAR);

callStmt.registerOutParameter(2, Types.VARCHAR);

cs.execute();

con.close();

}

catch (Exception e) {

/* exception handling logic goes here */

}

Page 20: ® IBM Software Group © IBM Corporation QUY Thai Duy – ITFac DLU quytd@dlu.edu.vn, thaiduyquy@gmail.com Lesson 12: SQL PL Stored Procedures.

IBM Software Group

Inline SQL PL

SQL PL = SQL Procedural Language

Inline SQL PL = SQL PL subset supported within a dynamic SQL statement, triggers and UDFs

Page 21: ® IBM Software Group © IBM Corporation QUY Thai Duy – ITFac DLU quytd@dlu.edu.vn, thaiduyquy@gmail.com Lesson 12: SQL PL Stored Procedures.

IBM Software Group

Example: Randomly populating a table

Pre-req:

Inline SQL PL:

create sequence myseqcreate table T1 (id bigint, data char(100), insert_ts timestamp)

begin atomicdeclare cnt INT default 0;while (cnt < 20000) do

insert into t1 values (nextval for MYSEQ,(select case

when (rand() < 0.5) then nullelse space(int(rand()*100))

end case from sysibm.sysdummy1),current timestamp);

set cnt=cnt+1;end while;

end

Page 22: ® IBM Software Group © IBM Corporation QUY Thai Duy – ITFac DLU quytd@dlu.edu.vn, thaiduyquy@gmail.com Lesson 12: SQL PL Stored Procedures.

IBM Software Group

User-Defined Functions

Functions always return a value

Some built-in functions already exist out-of-the-box Eg: SUM(), AVG(), DIGITS(), etc.

Can create UDFs in: SQL PL, C/C++, Java, CLR (Common Language Runtime), and OLE

(Object Linking and Embedding)

In this workshop, we focus on SQL PL functions because of their simplicity and popularity

Page 23: ® IBM Software Group © IBM Corporation QUY Thai Duy – ITFac DLU quytd@dlu.edu.vn, thaiduyquy@gmail.com Lesson 12: SQL PL Stored Procedures.

IBM Software Group

Types of functions Scalar functions

Return a single value

Cannot change database state (i.e. no INSERT, UPDATE, DELETE statements allowed)

Example: COALESCE( ), SUBSTR( )

Table functions Return values in a table format

Called in the FROM clause of a query

Can change database state (i.e. allow INSERT, UPDATE, DELETE statements)

Example: SNAPSHOT_DYN_SQL( ), MQREADALL( )

Others type of functions (not covered in this course): Row functions

Column functions

Page 24: ® IBM Software Group © IBM Corporation QUY Thai Duy – ITFac DLU quytd@dlu.edu.vn, thaiduyquy@gmail.com Lesson 12: SQL PL Stored Procedures.

IBM Software Group

Scalar function Scalar functions take input values and return a single value

Example:

CREATE FUNCTION deptname(p_empid VARCHAR(6))RETURNS VARCHAR(30)SPECIFIC deptnameBEGIN ATOMIC

DECLARE v_department_name VARCHAR(30);DECLARE v_err VARCHAR(70);SET v_department_name = (

SELECT d.deptname FROM department d, employee eWHERE e.workdept=d.deptno AND e.empno= p_empid);

SET v_err = 'Error: employee ' || p_empid || ' was not found';IF v_department_name IS NULL THEN

SIGNAL SQLSTATE '80000' SET MESSAGE_TEXT=v_err;END IF;

RETURN v_department_name;END

Page 25: ® IBM Software Group © IBM Corporation QUY Thai Duy – ITFac DLU quytd@dlu.edu.vn, thaiduyquy@gmail.com Lesson 12: SQL PL Stored Procedures.

IBM Software Group

Invoking Scalar UDFs

Scalar UDFs can be invoked in SQL statements wherever a scalar value is expected, or in a VALUES clause

SELECT DEPTNAME(‘000010’) FROM SYSIBM.SYSDUMMY1

VALUES DEPTNAME(‘000010’)

Page 26: ® IBM Software Group © IBM Corporation QUY Thai Duy – ITFac DLU quytd@dlu.edu.vn, thaiduyquy@gmail.com Lesson 12: SQL PL Stored Procedures.

IBM Software Group

Table UDFs

Return a table of rows

Used in the FROM clause of a query

Similar to a view, except more powerful because data modification statements (INSERT/UPDATE/DELETE) can be performed

Typically used to return a table and keep an audit record

Page 27: ® IBM Software Group © IBM Corporation QUY Thai Duy – ITFac DLU quytd@dlu.edu.vn, thaiduyquy@gmail.com Lesson 12: SQL PL Stored Procedures.

IBM Software Group

Table function example

A function which enumerates a set of employees of a department

CREATE FUNCTION getEnumEmployee(p_dept VARCHAR(3))RETURNS TABLE

(empno CHAR(6),lastname VARCHAR(15),firstnme VARCHAR(12))

SPECIFIC getEnumEmployeeRETURN

SELECT e.empno, e.lastname, e.firstnmeFROM employee eWHERE e.workdept=p_dept

Page 28: ® IBM Software Group © IBM Corporation QUY Thai Duy – ITFac DLU quytd@dlu.edu.vn, thaiduyquy@gmail.com Lesson 12: SQL PL Stored Procedures.

IBM Software Group

Calling a Table function

Used in the FROM clause of an SQL statement

The TABLE() function must be applied and must be aliased.

Page 29: ® IBM Software Group © IBM Corporation QUY Thai Duy – ITFac DLU quytd@dlu.edu.vn, thaiduyquy@gmail.com Lesson 12: SQL PL Stored Procedures.

IBM Software Group

Triggers

A trigger is a database object defined on a table and fired when an INSERT, UPDATE, or DELETE operation is performed.

Activate (“fire”) automatically

Operations that cause triggers to fire are called triggering SQL statements

Page 30: ® IBM Software Group © IBM Corporation QUY Thai Duy – ITFac DLU quytd@dlu.edu.vn, thaiduyquy@gmail.com Lesson 12: SQL PL Stored Procedures.

IBM Software Group

Types of Triggers BEFORE

activation before row is inserted, updated or deleted

Operations performed by this trigger cannot activate other triggers (i.e. INSERT, UPDATE, and DELETE operations are not permitted)

AFTER Activated after the triggering SQL statement has executed to successful

completion

May activate other triggers (cascading permitted up to 16 levels)

INSTEAD OF Defined on views

Logic defined in the trigger is executed instead of the triggering SQL statement

Page 31: ® IBM Software Group © IBM Corporation QUY Thai Duy – ITFac DLU quytd@dlu.edu.vn, thaiduyquy@gmail.com Lesson 12: SQL PL Stored Procedures.

IBM Software Group

A Simple BEFORE Trigger

CREATE TRIGGER default_class_endNO CASCADE BEFORE INSERT ON cl_schedREFERENCING NEW AS n

FOR EACH ROWMODE DB2SQL

WHEN (n.ending IS NULL)SET n.ending = n.starting + 1 HOUR

define qualifier for new values

Optional WHEN

if no value provided oninsert, column is NULL

Page 32: ® IBM Software Group © IBM Corporation QUY Thai Duy – ITFac DLU quytd@dlu.edu.vn, thaiduyquy@gmail.com Lesson 12: SQL PL Stored Procedures.

IBM Software Group

Quicklab: BEFORE trigger using SQL PLCREATE TRIGGER validate_sched

NO CASCADE BEFORE INSERT ON cl_sched

REFERENCING NEW AS n

FOR EACH ROW

MODE DB2SQL

BEGIN ATOMIC

-- supply default value for ending time if null

IF (n.ending IS NULL) THEN

SET n.ending = n.starting + 1 HOUR;

END IF;

-- ensure that class does not end beyond 9pm

IF (n.ending > '21:00') THEN

SIGNAL SQLSTATE '80000'

SET MESSAGE_TEXT='class ending time is beyond 9pm';

ELSEIF (n.DAY=1 or n.DAY=7) THEN

SIGNAL SQLSTATE '80001'

SET MESSAGE_TEXT='class cannot be scheduled on a weekend';

END IF;

END

atomic, dynamiccompound SQL

Page 33: ® IBM Software Group © IBM Corporation QUY Thai Duy – ITFac DLU quytd@dlu.edu.vn, thaiduyquy@gmail.com Lesson 12: SQL PL Stored Procedures.

IBM Software Group

A Simple AFTER Trigger

Similar to BEFORE triggers, except that INSERT, UPDATE and DELETE are supported

Prereq: CREATE TABLE audit (mytimestamp timestamp, comment varchar (1000))

CREATE TRIGGER audit_emp_salAFTER UPDATE OF salary ON employeeREFERENCING OLD AS o NEW AS nFOR EACH ROWMODE DB2SQL

INSERT INTO audit VALUES (CURRENT TIMESTAMP, ' Employee ' || o.empno || 'salary changed from ' || CHAR(o.salary) || ' to

' || CHAR(n.salary) || ' by ' || USER)