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

Slides:



Advertisements
Similar presentations
PL/SQL.
Advertisements

Chapter 8 Advanced SQL Pearson Education © Chapter 8 - Objectives u How to use the SQL programming language u How to use SQL cursors u How to create.
BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures.
Oracle PL/SQL IV Exceptions Packages.
AN INTRODUCTION TO PL/SQL Mehdi Azarmi 1. Introduction PL/SQL is Oracle's procedural language extension to SQL, the non-procedural relational database.
PL/SQL. Introduction to PL/SQL PL/SQL is the procedure extension to Oracle SQL. It is used to access an Oracle database from various environments (e.g.
SQL*PLUS, PLSQL and SQLLDR Ali Obaidi. SQL Advantages High level – Builds on relational algebra and calculus – Powerful operations – Enables automatic.
® IBM Software Group © IBM Corporation QUY Thai Duy – ITFac DLU Lesson 2: The DB2 Environment.
Stored Procedure, UDF and Triggers Pertemuan 9 Matakuliah: T0413 Tahun: 2009.
Stored Procedure Language Stored Procedure Overview Stored Procedure is a function in a shared library accessible to the database server can also write.
Introduction to PL/SQL Lecture 0 – Self Study Akhtar Ali.
SEMESTER 1, 2013/2014 DB2 APPLICATION DEVELOPMENT OVERVIEW.
Structured Query Language (SQL) A2 Teacher Up skilling LECTURE 2.
PL / SQL P rocedural L anguage / S tructured Q uery L anguage Chapter 7 in Lab Reference.
Cursor and Exception Handling By Nidhi Bhatnagar.
Lecture 4 PL/SQL language. PL/SQL – procedural SQL Allows combining procedural and SQL code PL/SQL code is compiled, including SQL commands PL/SQL code.
Stored Procedures, Transactions, and Error-Handling
CHAPTER:14 Simple Queries in SQL Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्सजेंड़र ) PGT(CS),KV JHAGRAKHAND.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM. 5.1 © Copyright IBM Corporation 2008 DB2 9 Fundamentals.
Working with Data Objects Pertemuan 6 Matakuliah: T0413 Tahun: 2009.
B ASIC SQL P ROCEDURE S TRUCTURE. U NIT OBJECTIVES After completing this unit, you should be able to: Describe the structure of an SQL procedure Explain.
Stored procedures1 Stored procedures and functions Procedures and functions stored in the database.
Overview · What is PL/SQL · Advantages of PL/SQL · Basic Structure of a PL/SQL Block · Procedure · Function · Anonymous Block · Types of Block · Declaring.
PL/SQL A BRIEF OVERVIEW DAVID WILSON. PL/SQL User’s Guide and Reference PL/SQL User’s Guide and Reference.
Triggers and Stored Procedures in DB 1. Objectives Learn what triggers and stored procedures are Learn the benefits of using them Learn how DB2 implements.
Introduction to the new mainframe © Copyright IBM Corp., All rights reserved. Chapter 12 Understanding database managers on z/OS.
Advanced SQL: Cursors & Stored Procedures
CpSc 462/662: Database Management Systems (DBMS) (TEXNH Approach) Stored Procedure James Wang.
Stored Procedures Week 9. Test Details Stored Procedures SQL can call code written in iSeries High Level Languages –Called stored procedures SQL has.
PL / SQL By Mohammed Baihan. What is PL/SQL? PL/SQL stands for Procedural Language extension of SQL. PL/SQL is a combination of SQL along with the procedural.
Programmatic SQL Shaista Khan CS 157B. Topic Embedded SQL statements in high-level programming languages.
School of Computing and Management Sciences © Sheffield Hallam University SQL is non-procedural –designed to be relatively approachable to non- programmers.
© 2011 IBM Corporation 15 June 2011 Triggers and Stored Procedure Language (SPL)
Advanced SQL: Triggers & Assertions
Objectives Database triggers and syntax
PL/SQLPL/SQL Oracle10g Developer: PL/SQL Programming Chapter 9 Database Triggers.
Chapter 4 An Introduction to SQL. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.4-2 Topics in this Chapter SQL: History and Overview The.
PL/SQLPL/SQL Oracle11g: PL/SQL Programming Chapter 9 Database Triggers.
PL/SQLPL/SQL Oracle10g Developer: PL/SQL Programming Chapter 9 Database Triggers.
Development Overview Pertemuan 11 Matakuliah: T0413 Tahun: 2009.
©Silberschatz, Korth and Sudarshan5.1Database System Concepts - 6 th Edition Procedural Constructs in SQL Chapter 5.
PL/SQL programming Procedures and Cursors Lecture 1 [Part 2]
PRACTICE OVERVIEW PL/SQL Part Your stored procedure, GET_BUDGET, has a logic problem and must be modified. The script that contains the procedure.
Chapter 8 Advanced SQL Pearson Education © Chapter 8 - Objectives How to use the SQL programming language How to use SQL cursors How to create stored.
Advanced SQL: Cursors & Stored Procedures Instructor: Mohamed Eltabakh 1.
Last Updated : 27 th April 2004 Center of Excellence Data Warehousing Group Teradata RDBMS Concepts.
Kingdom of Saudi Arabia Ministry of Higher Education Al-Imam Muhammad Ibn Saud Islamic University College of Computer and Information Sciences Overview.
Constraints and Views Chap. 3-5 continued (7 th ed. 5-7)
Retele de senzori Curs 2 - 1st edition UNIVERSITATEA „ TRANSILVANIA ” DIN BRAŞOV FACULTATEA DE INGINERIE ELECTRICĂ ŞI ŞTIINŢA CALCULATOARELOR.
SQL Triggers, Functions & Stored Procedures Programming Operations.
Programming in postgreSQL with PL/pgSQL ProceduralLanguageextension topostgreSQL 1.
CS422 Principles of Database Systems Stored Procedures and Triggers Chengyu Sun California State University, Los Angeles.
1. Advanced SQL Functions Procedural Constructs Triggers.
CS320 Web and Internet Programming SQL and MySQL
Dynamic SQL: Writing Efficient Queries on the Fly
Chapter 5: Advanced SQL Database System concepts,6th Ed.
Error Handling Summary of the next few pages: Error Handling Cursors.
CPSC-310 Database Systems
CS122B: Projects in Databases and Web Applications Spring 2017
CS122B: Projects in Databases and Web Applications Winter 2017
Dynamic SQL: Writing Efficient Queries on the Fly
PL/SQL week10.
Oracle9i Developer: PL/SQL Programming Chapter 8 Database Triggers.
PRACTICE OVERVIEW PL/SQL Part - 1.
CS3220 Web and Internet Programming SQL and MySQL
Information Management
Chapter 8 Advanced SQL Pearson Education © 2009.
Prof. Arfaoui. COM390 Chapter 9
CS3220 Web and Internet Programming SQL and MySQL
Stored Procedure Language
Presentation transcript:

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

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.

IBM Software Group 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

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

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

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

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

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 )

IBM Software Group Compound statements

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

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;

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

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

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

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)

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

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

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 */ }

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

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

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

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

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

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

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

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

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.

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

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

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

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

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)