Oct 6, 2009 1:00 p.m. – 2:00 p.m. Platform: DB2 for LUW Serge Rielau IBM Canada Session: C06 SQL PL in DB2 9.7 all grown up.

Slides:



Advertisements
Similar presentations
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.
Advertisements

® IBM Software Group © IBM Corporation QUY Thai Duy – ITFac DLU Lesson 12: SQL PL Stored Procedures.
O VERVIEW OF SQL PL L ANGUAGE E LEMENTS & M ODULES.
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.
Murali Mani Persistent Stored Modules (Stored Procedures) : PSM.
Lecture-5 Though SQL is the natural language of the DBA, it suffers from various inherent disadvantages, when used as a conventional programming language.
Chapter 9: Advanced SQL and PL/SQL Topics Guide to Oracle 10g.
Creating Packages. 2 home back first prev next last What Will I Learn? Describe the reasons for using a package Describe the two components of a package:
A Guide to Oracle9i1 Advanced SQL And PL/SQL Topics Chapter 9.
Introduction to PL/SQL Lecture 0 – Self Study Akhtar Ali.
SEMESTER 1, 2013/2014 DB2 APPLICATION DEVELOPMENT OVERVIEW.
Introduction to PL/SQL. Procedural Language extension for SQL Oracle Proprietary 3GL Capabilities Integration of SQL Portable within Oracle data bases.
Advanced Databases Advanced PL/SQL Programming: Procedure, Function and Package.
PL / SQL P rocedural L anguage / S tructured Q uery L anguage Chapter 7 in Lab Reference.
Virtual Private Databases Dr. Gabriel. 2 Overview of Virtual Private Databases A VPD deals with data access VPD controls data access at the row or column.
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.
PL/SQLPL/SQL Oracle10g Developer: PL/SQL Programming Chapter 7 PL/SQL Packages.
Creating Dynamic Web Pages Using PHP and MySQL CS 320.
Oracle PL/SQL Practices. Critical elements of PL/SQL Best Practices Build your development toolbox Unit test PL/SQL programs Optimize SQL in PL/SQL programs.
Serge Rielau IBM Canada Session: F13 Shifting Shapes Transforming the way you evolve your DB schema Oct 7, :45 p.m. – 4:45 p.m. Platform: DB2 for.
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.
Copyright © Curt Hill Stored Procedures In Transact-SQL.
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.
CS178 Database Management PL/SQL session 8 References: ORACLE 9i PROGRAMMING A Primer Rajshekhar Sunderraman.
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.
Chapter 15 Introduction to PL/SQL. Chapter Objectives  Explain the benefits of using PL/SQL blocks versus several SQL statements  Identify the sections.
SQL Fundamentals  SQL: Structured Query Language is a simple and powerful language used to create, access, and manipulate data and structure in the database.
What is a Package? A package is an Oracle object, which holds other objects within it. Objects commonly held within a package are procedures, functions,
Objectives Database triggers and syntax
PL/SQLPL/SQL Oracle10g Developer: PL/SQL Programming Chapter 9 Database Triggers.
Chapter 9: Advanced SQL and PL/SQL Guide to Oracle 10g.
Dynamic SQL. 2 home back first prev next last What Will I Learn? Recall the stages through which all SQL statements pass Describe the reasons for using.
PL/SQLPL/SQL Oracle11g: PL/SQL Programming Chapter 9 Database Triggers.
PL/SQLPL/SQL Oracle10g Developer: PL/SQL Programming Chapter 9 Database Triggers.
DATABASE PROGRAMS CS 260 Database Systems. Overview  Introduction  Anonymous blocks  Oracle’s PL/SQL language basics  Conditions and loops  Cursors.
Learningcomputer.com SQL Server 2008 –Views, Functions and Stored Procedures.
PRACTICE OVERVIEW PL/SQL Part Your stored procedure, GET_BUDGET, has a logic problem and must be modified. The script that contains the procedure.
Stored Procedures / Session 4/ 1 of 41 Session 4 Module 7: Introducing stored procedures Module 8: More about stored procedures.
Oracle10g Developer: PL/SQL Programming1 Objectives Named program units How to identify parameters The CREATE PROCEDURE statement Creating a procedure.
Text TCS INTERNAL Oracle PL/SQL – Introduction. TCS INTERNAL PL SQL Introduction PLSQL means Procedural Language extension of SQL. PLSQL is a database.
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.
CS422 Principles of Database Systems Stored Procedures and Triggers Chengyu Sun California State University, Los Angeles.
1. Advanced SQL Functions Procedural Constructs Triggers.
Oracle9i Developer: PL/SQL Programming Chapter 6 PL/SQL Packages.
Preface IIntroduction Course Objectives I-2 Oracle Complete Solution I-3 Course Agenda I-4 Tables Used in This Course I-5 The Order Entry Schema I-6 The.
COMP 430 Intro. to Database Systems
Data Virtualization Tutorial: Introduction to SQL Script
PL/SQL MULTIPLE CHOICE QUESTION.
PL/SQL.
Chapter 5: Advanced SQL Database System concepts,6th Ed.
UNIT - V STORED PROCEDURE.
Error Handling Summary of the next few pages: Error Handling Cursors.
PL/SQL Package Week 8.
PL/SQL Scripting in Oracle:
Client Access, Queries, Stored Procedures, JDBC
Oracle9i Developer: PL/SQL Programming Chapter 8 Database Triggers.
PRACTICE OVERVIEW PL/SQL Part - 1.
MATERI PL/SQL Procedures Functions Packages Database Triggers
Chapter 8 Advanced SQL Pearson Education © 2009.
Prof. Arfaoui. COM390 Chapter 9
Prof. Arfaoui. COM390 Chapter 7
Improving the Performance of Functions
Presentation transcript:

Oct 6, :00 p.m. – 2:00 p.m. Platform: DB2 for LUW Serge Rielau IBM Canada Session: C06 SQL PL in DB2 9.7 all grown up

2 Agenda Motivation Virtual tour Emphasis on value, not on syntax details

3 Evolution of SQL PL VersionFocus 7Initial release 8.1Performance 8.2Native SQL PL 9Performance 9.5App dev. 9.7Performance ?

4 What’s in it for me? Not just new syntax enhancements here and there Reducing TCO Where are the savings Application development cost Application maintenance cost Enablement cost

5 Audience Poll Where does it hurt ?

6 Overview Full SQL PL support across the board UDFs, Triggers, Blocks Data structures Rows Arrays of rows (local and global) Associative arrays Modules Cursor data type Data type anchoring Global named exceptions Built-in module library CALL statement CONSTANT

7 Full SQL PL across the board Inlined vs. compiled SQL PL Inlined: UDF and triggers inlined in SQL statement Compiled: SP is compiled into a separate object Inlined Performane advantage (no context switch between SQL and SQL PL) Several SQL PL language features not supported: Cursor and result set handling Error handling Dynamic SQL Compiled Full SQL PL Available so far in SPs only

8 Vnext: Full SQL PL in more places DB2 9.5DB2 9.7 SPs Scalar UDFsLimited DPF Table UDFs Row TriggersNon DPF Stmt Triggers Block

9 Scenario for running example -- Materials table CREATE TABLE materials (id INTEGER, name VARCHAR(100), description VARCHAR(256)) INSERT INTO materials VALUES (1, ‘2X4', ’12-feet long two by four’), (3, ‘nail', ’2 inch drywall nail’), (7, ‘drywall', ’ 8x12-feet drywall -- Suppliers table CREATE TABLE suppliers (id INTEGER, name VARCHAR(100), VARCHAR(100)) INSERT INTO suppliers VALUES (74, ‘Bob the builder', (33, -- Supplier/Material table CREATE TABLE supProd (suppId INTEGER, prodId INTEGER, qty INTEGER) INSERT INTO supProd VALUES (74, 3, 12000), (74, 7, 850), (33, 7, Problem statement “Define a trigger on materials table such that when a new material is inserted, the trigger will send to each of the suppliers of that material to request a quote”

10 Full SQL PL: example CREATE TRIGGER sendQuoteReqs AFTER INSERT ON materials REFERENCING new AS new FOR EACH ROW BEGIN DECLARE suppId INTEGER; DECLARE suppName VARCHAR (128); DECLARE supp VARCHAR (128); DECLARE cur1 CURSOR CONSTANT CURSOR FOR SELECT id, name, FROM suppliers s, supProd sp WHERE s.id = sp.suppId AND new.id = sp.prodId; DECLARE CONTINUE HANDLER FOR .EmalNotSent INSERT INTO errorLog VALUES (‘Failed to send to supplier ‘ || suppName); OPEN cur1; -- Send to each supplier of this product FETCH cur1 INTO suppId, suppName, supp ; WHILE cur1 IS FOUND DO CALL sendQuoteRequest (suppId, suppName, supp , new.id, new.name); FETCH cur1 INTO suppId, suppName, supp ; END WHILE;

11 ROW data type Ubiquitous “struct” or “record” type Even more natural in database procedural language What can be done with rows Single variable to fetch and insert Can pass a parameters and return from UDFs Can define global and module variables Can use them to build arrays of rows (lightweight tables + compact array syntax)

12 ROW data type In previous example, unit of info was supplier But supplier info split into several variables Must carry variables around on all operations on supplier However, when dealing with materials, DB2 didn’t create a variable per column. It created a variable for the whole row CREATE TRIGGER… REFERENCING new AS new … Row types let users do the same

13 ROW data type: example CREATE TYPE supplierType AS ROW ( suppId INTEGER, suppName VARCHAR (100), supp VARCHAR (100) CREATE TRIGGER sendQuoteReqs AFTER INSERT ON materials REFERENCING new AS new FOR EACH ROW BEGIN DECLARE supp supplierType; DECLARE cur1 CURSOR CONSTANT CURSOR FOR SELECT id, name, FROM suppliers s, supProd sp WHERE s.id = sp.suppId AND new.id = sp.prodId;... FETCH cur1 INTO supp; … CALL sendQuoteRequest (supp, new.id, new.name); …

14 Anchored row type We didn’t have to specify a type for the trigger transition variable All DB2 needs to know is what table the trigger is associated with … AFTER INSERT ON materials … Why not let the user do the same for row types ? CREATE TYPE supplierType AS ROW ( suppId INTEGER, suppName VARCHAR (128), supp VARCHAR (128) CREATE TYPE supplierRow1 AS ANCHOR ROW

15 Anchored row type: example But… why define a type at all? CREATE TRIGGER sendQuoteReqs AFTER INSERT ON materials REFERENCING new AS new FOR EACH ROW BEGIN DECLARE supp ANCHOR ROW suppliers; …

16 Anchored row type Available in: Local variables Global variables Parameters and return types Value Less code to write Code automatically in-sync with data Can anchor on tables and or cursors

17 Anchored row type: cursor anchor New requirement: in addition to supplier data, must fetch quantity CREATE TRIGGER sendQuoteReqs AFTER INSERT ON materials REFERENCING new AS new FOR EACH ROW BEGIN DECLARE cur1 CURSOR CONSTANT CURSOR FOR SELECT id, name, , qty FROM suppliers s, supProd sp WHERE s.id = sp.suppId AND new.id = sp.prodId; DECLARE suppAndQty ANCHOR ROW cur1; … FETCH cur1 INTO suppAndQty; … END

18 Scalar anchoring Same concept, but at scalar level Can anchor on a column or on another variable CREATE TYPE supplierType2 AS ROW ( suppId ANCHOR supplier.id, suppName ANCHOR supplier.name, supp ANCHOR supplier. CREATE VARIABLE id ANCHOR CREATE FUNCTION get (id ANCHOR supplier.id) RETURN ANCHOR supplier.id

19 Associative Arrays: example New requirement: keep track of how many quotes we’ve requested from each supplier CREATE TYPE reqList AS INT CREATE VARIABLE reqsPerSupp CREATE TRIGGER … … -- Send to each supplier of this product FETCH cur1 INTO suppAndQty; WHILE cur1 IS FOUND DO CALL sendQuoteRequest (suppAndQty, new.id, new.name); SET reqsPerSupp[suppId] = CASE WHEN reqsPerSupp[suppId] IS NULL THEN 1 ELSE reqsPerSupp[suppId] + 1 END CASE; FETCH cur1 INTO suppAndQty; END WHILE;

20 Associative Arrays Conventional arrays are “dense” CREATE TYPE arrTyp AS INT … DECLARE a arrTyp; SET a[1500] = 100; /* a has now 1500 elements */ Associative arrays are “sparse” CREATE TYPE arrTyp AS INT … DECLARE a arrTyp; SET a[1500] = 100; /* a has now 1 element */

21 Associative Arrays Index can be any integer type or VARCHAR of any length Element can be any scalar type or a row type CREATE TYPE arrType AS suppTyp ARRAY[VARCHAR(100)]; … DECLARE var arrType; SET var[‘Supplier One’] = supp; /* supp is a row */ Can use Scalar Anchoring on both element and index CREATE TYPE suppArr AS ANCHOR ROW suppliers ARRAY[ANCHOR Can be used in variables, parameters, UDF return type and global/module variables

22 Modules Module = bundle of several related objects SPs, UDFs, global variables and cursors, types, conditions Similar to a class in OO languages (but single instance) Bundle canned applications, libraries Impose structure on medium-sized and large apps Use module to “hide” implementation

23 Modules: example CREATE OR REPLACE MODULE ALTER MODULE hideArray ADD TYPE reqList AS INT ARRAY[ANCHOR TO ALTER MODULE hideArray ADD VARIABLE reqsPerSupp ALTER MODULE hideArray PUBLISH PROCEDURE incSuppCount(IN suppId ANCHOR suppliers.id) BEGIN SET reqsPerSupp[suppId] = CASE WHEN reqsPerSupp[suppId] IS NULL THEN 1 ELSE reqsPerSupp[suppId] + 1 END CASE;

24 Modules - benefits Code organization/structure Related routines share variables, types and conditions Scoping Possibilities of name conflicts CALL mySchema.myModule.myProc() Several users can deploy same module under different schema, with no name clashes Information hiding Each object can be “public” or “private” Global privilege control Instead of granting/revoking on each SP, UDF or variable

25 Modules: module specification CREATE OR REPLACE MODULE ALTER MODULE myMod PUBLISH CONDITION ALTER MODULE myMod PUBLISH FUNCTION myFunc(val1 ANCHOR myTab.col1) RETURNS ALTER MODULE myMod PUBLISH PROCEDURE myProc(OUT parm1 ANCHOR GRANT EXECUTE ON MODULE myMod TO Grants user joe execute privilege on all routines and access to all variables and types in myMod

26 Modules: module implementation ALTER MODULE myMod DROP ALTER MODULE myMod ADD VARIABLE pkgVar ANCHOR ALTER MODULE myMod ADD FUNCTION myFunc() RETURNS INT BEGIN DECLARE var1 INT; SELECT * INTO var1 FROM myTab WHERE col1 < pkgVar; IF (var1 > maxVal) THEN SIGNAL badCode; END IF; RETURN var1; ALTER MODULE myMod ADD PROCEDURE myProc(OUT parm1 ANCHOR myTab.col2) BEGIN DECLARE var1 INT; DECLARE EXIT HANDLER FOR badCode BEGIN END; SET var1 = myFunc();

27 CURSOR data type Cursors are values Pass cursors as parameters Cursor global variable Function that returns a cursor Cursor OUT parameters can be returned to JDBC clients Parameterized cursors Cursor predicates Can open cursor in a procedure and assign to global variable. Cursor becomes a global cursor. Closed when there are no variables referencing it.

28 CURSOR data type: example CREATE FUNCTION getSupps(prodId IN ANCHOR materials.id) RETURNS CURSOR BEGIN DECLARE cur CURSOR; SET cur = CURSOR FOR SELECT id, name, FROM suppliers s, supProd sp WHERE s.id = sp.suppId AND sp.prodId = prodId; OPEN cur; RETURN cur; END % CREATE PROCEDURE send s (cur CURSOR) BEGIN DECLARE varCur myCurTyp; DECLARE supp ANCHOR ROW suppliers; -- Send to each supplier of this product FETCH cur INTO supp; WHILE cur IS FOUND DO CALL sendQuoteRequest (supp); FETCH cur INTO supp; END WHILE; END %

29 CURSOR data type: example CREATE TRIGGER sendQuoteReqs AFTER INSERT ON materials REFERENCING new AS new FOR EACH ROW BEGIN DECLARE CONTINUE HANDLER FOR .EmalNotSent INSERT INTO errorLog VALUES (‘Failed to send to supplier ‘ || suppName); DECLARE cur CURSOR; SET cur = getSupps(new.id); CALL send s(cur);

30 Anonymous blocks Server-side SQL scripting One-time maintenance operations on the db Quick reports Example: validate shipments and report errors BEGIN FOR s IN SELECT * FROM localShipments DO BEGIN DECLARE CONTINUE HANDLER FOR shipments.invalidOrigin CALL print('ERROR: Bad shipment. Date =' || s.date || ', Origin = ' || s.origin); CALL validateShipment (‘|’ || s.origin || s.description); END; END FOR; END Cached on first execution Can use parameter markers

31 CALL enhancements Default values for parameters CREATE PROCEDURE logError (id INT, message VARCHAR(200) DEFAULT ‘No message’) … The following statements are equivalent CALL logError(10) CALL logError(12, DEFAULT) Named parameters CALL logError(message => ‘limit exceeded’, id => 31)

32 CONSTANT Constant global variables: application-wide constants CREATE VARIABLE maxWithdrawal FLOAT CONSTANT Module version: ALTER MODULE atm PUBLISH VARIABLE maxWithdrawal FLOAT CONSTANT Constant local variables DECLARE maxArrSize INT CONSTANT 256;

33 Conclusions SQL PL evolving from simple procedural control language to full programming language Reduced app dev, app maintenance and app enablement Note: DB2 also provides full PL/SQL support

34 Q&A ?

35 Serge Rielau IBM Canada Session: C06 SQL PL in DB2 9.7 all grown up