Presentation is loading. Please wait.

Presentation is loading. Please wait.

® IBM Software Group © IBM Corporation QUY Thai Duy – ITFac DLU Lesson 12: SQL PL Stored Procedures.

Similar presentations

Presentation on theme: "® IBM Software Group © IBM Corporation QUY Thai Duy – ITFac DLU Lesson 12: SQL PL Stored Procedures."— Presentation transcript:

1 ® IBM Software Group © IBM Corporation QUY Thai Duy – ITFac DLU Lesson 12: SQL PL Stored Procedures

2 IBM Software Group Agenda  Stored procedures overview  IBM Data Studio  SQL PL Stored Procedures basics  Cursors  Errors & condition handlers  Flow control  Calling Stored Procedures  User Define Function.  Trigger.

3 IBM Software Group Stored Procedures

4 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

5 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

6 IBM Software Group Basic stored procedure structure  is a single statement, or a set of statements  grouped by BEGIN [ATOMIC]... END

7 IBM Software Group Optional stored procedure attributes  LANGUAGE SQL  RESULT SETS (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...

8 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

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

10 IBM Software Group Compound statements

11 IBM Software Group Variable declaration DECLARE var_name [ DEFAULT value];  Note: Default value is NULL  Examples: DECLARE temp1 SMALLINT DEFAULT 0; DECLARE temp2 INTEGER DEFAULT 10; DECLARE temp3 DECIMAL(10,2) DEFAULT ; DECLARE temp4 REAL DEFAULT 10.1; DECLARE temp5 DOUBLE DEFAULT ; DECLARE temp6 BIGINT DEFAULT 10000; DECLARE temp7 CHAR(10) DEFAULT 'yes'; DECLARE temp8 VARCHAR(10) DEFAULT 'hello'; DECLARE temp9 DATE DEFAULT ' '; DECLARE temp10 TIME DEFAULT '1:50 PM'; DECLARE temp11 TIMESTAMP DEFAULT ' '; DECLARE temp12 CLOB(2G); DECLARE temp13 BLOB(2G);

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

13 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 SQL SPECIFIC myP2 BEGIN -- my second SQL procedure SET v_p2 = v_p2 + v_p1; SET v_p3 = v_p1; END

14 IBM Software Group Cursors  cursor declaration and usage: DECLARE CURSOR [WITH RETURN ] ; OPEN ; FETCH INTO CLOSE ;  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

15 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

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

17 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

18 IBM Software Group Quicklab: Dynamic SQL  prerequisite: create table T2 (c1 int, c2 int) CREATE PROCEDURE dyn1 (IN value1 INT, IN value2 INT) SPECIFIC dyn1 BEGIN 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

19 IBM Software Group Calling Stored Procedures from a Java Application Try { // 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 */ }

20 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

21 IBM Software Group Example: Randomly populating a table  Pre-req:  Inline SQL PL: create sequence myseq create table T1 (id bigint, data char(100), insert_ts timestamp) begin atomic declare cnt INT default 0; while (cnt < 20000) do insert into t1 values ( nextval for MYSEQ, (select case when (rand() < 0.5) then null else space(int(rand()*100)) end case from sysibm.sysdummy1), current timestamp); set cnt=cnt+1; end while; end

22 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

23 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

24 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 deptname BEGIN ATOMIC DECLARE v_department_name VARCHAR(30); DECLARE v_err VARCHAR(70); SET v_department_name = ( SELECT d.deptname FROM department d, employee e WHERE 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

25 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’)

26 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

27 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 getEnumEmployee RETURN SELECT e.empno, e.lastname, e.firstnme FROM employee e WHERE e.workdept=p_dept

28 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.

29 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

30 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

31 IBM Software Group A Simple BEFORE Trigger CREATE TRIGGER default_class_end NO CASCADE BEFORE INSERT ON cl_sched REFERENCING NEW AS n FOR EACH ROW MODE DB2SQL WHEN (n.ending IS NULL) SET n.ending = n.starting + 1 HOUR define qualifier for new values Optional WHEN if no value provided on insert, column is NULL

32 IBM Software Group Quicklab: BEFORE trigger using SQL PL CREATE 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, dynamic compound SQL

33 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_sal AFTER UPDATE OF salary ON employee REFERENCING OLD AS o NEW AS n FOR EACH ROW MODE DB2SQL INSERT INTO audit VALUES ( CURRENT TIMESTAMP, ' Employee ' || o.empno || ' salary changed from ' || CHAR(o.salary) || ' to ' || CHAR(n.salary) || ' by ' || USER)

Download ppt "® IBM Software Group © IBM Corporation QUY Thai Duy – ITFac DLU Lesson 12: SQL PL Stored Procedures."

Similar presentations

Ads by Google