1 Stored Procedures in MySQL Part I. 2 Objectives SQL Vs. MySQL SP MySQL SP Parameters MySQL SP Control Structures.

Slides:



Advertisements
Similar presentations
PHP II Interacting with Database Data. The whole idea of a database-driven website is to enable the content of the site to reside in a database, and to.
Advertisements

PL/SQL.
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.
Stored Procedure Language Stored Procedure Overview Stored Procedure is a function in a shared library accessible to the database server can also write.
Murali Mani Persistent Stored Modules (Stored Procedures) : PSM.
Chapter 4B: More Advanced PL/SQL Programming
Programming in Oracle with PL/SQL
Introduction to PL/SQL
DAT702.  Standard Query Language  Ability to access and manipulate databases ◦ Retrieve data ◦ Insert, delete, update records ◦ Create and set permissions.
Cursors in Pl/SQL Database 1. Practice. Sample Database The schema of the sample database is the following: Drinkers (name, occupation, birthday, salary)
PL/SQL Bulk Collections in Oracle 9i and 10g Kent Crotty Burleson Consulting October 13, 2006.
Bordoloi and Bock CURSORS. Bordoloi and Bock CURSOR MANIPULATION To process an SQL statement, ORACLE needs to create an area of memory known as the context.
Programming in Oracle with PL/SQL ProceduralLanguageExtension toSQL.
PL / SQL P rocedural L anguage / S tructured Q uery L anguage Chapter 7 in Lab Reference.
SQL Training Procedures & Functions. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. DB Procedures & Functions Procedures and Functions.
1 Introduction to PL/SQL. 2  Procedural programming language  Uses detailed instructions  Processes statements sequentially  Combines SQL commands.
Oracle10g Developer: PL/SQL Programming1 Objectives Manipulating data with cursors Managing errors with exception handlers Addressing exception-handling.
Chapter 4 Cursors and Exception Handling Oracle10g Developer:
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.
Dinamic SQL & Cursor. Why Dinamic SQL ? Sometimes there is a need to dynamically create a SQL statement on the fly and then run that command. This can.
Stored Procedures, Transactions, and Error-Handling
CHAPTER:14 Simple Queries in SQL Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्सजेंड़र ) PGT(CS),KV JHAGRAKHAND.
MySQL Stored Procedure and User-Defined Function ISYS 475.
CpSc 462/662: Database Management Systems (DBMS) (TEXNH Approach) Constraints, Triggers and Index James Wang.
SQL SQL Server : Overview SQL : Overview Types of SQL Database : Creation Tables : Creation & Manipulation Data : Creation & Manipulation Data : Retrieving.
Program with PL/SQL. Interacting with the Oracle Server.
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 Block Structures. What is PL SQL A good way to get acquainted with PL/SQL is to look at a sample program. PL/SQL combines the data manipulating.
Advanced SQL: Cursors & Stored Procedures
Program with PL/SQL Lesson 4. Writing Control Structure.
CpSc 462/662: Database Management Systems (DBMS) (TEXNH Approach) Stored Procedure James Wang.
Advanced SQL Instructor: Mohamed Eltabakh 1 Part II.
Stored Procedures Week 9. Test Details Stored Procedures SQL can call code written in iSeries High Level Languages –Called stored procedures SQL has.
CS146 References: ORACLE 9i PROGRAMMING A Primer Rajshekhar Sunderraman
Constraints, Triggers and Views COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, VEHARI.
Oracle PL/SQL. PL/SQL Originally modeled after ADA Originally modeled after ADA Created for Dept. of DefenseCreated for Dept. of Defense Allows expanded.
CIS4368: Advanced DatabaseSlide # 1 PL/SQL Dr. Peeter KirsSpring, 2003 PL/SQL.
BIS Database Systems School of Management, Business Information Systems, Assumption University A.Thanop Somprasong Chapter # 8 Advanced SQL.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
PL/SQL Block Structure DECLARE - Optional Variables, cursors, user-defined exceptions BEGIN - Mandatory SQL Statements PL/SQL Statements EXCEPTIONS - Optional.
Chapter 15 Introduction to PL/SQL. Chapter Objectives  Explain the benefits of using PL/SQL blocks versus several SQL statements  Identify the sections.
Database Management COP4540, SCS, FIU Oracle PL/SQL (Ch 10.5)
SQL Basics. What is SQL? SQL stands for Structured Query Language. SQL lets you access and manipulate databases.
School of Computing and Management Sciences © Sheffield Hallam University SQL is non-procedural –designed to be relatively approachable to non- programmers.
CMPE 226 Database Systems October 7 Class Meeting Department of Computer Engineering San Jose State University Fall 2015 Instructor: Ron Mak
PL/SQLPL/SQL Oracle10g Developer: PL/SQL Programming Chapter 9 Database Triggers.
Visual Programing SQL Overview Section 1.
Chapter 8 Advanced SQL Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
ITEC 224 Database Programming PL/SQL Lab Cursors.
Chapter 5 : Integrity And Security  Domain Constraints  Referential Integrity  Security  Triggers  Authorization  Authorization in SQL  Views 
implicit and an explicit cursor
Professor: Dr. Shu-Ching Chen TA: Hsin-Yu Ha Function, Trigger used in PosgreSQL.
DBTech VET / DBTechNet SQL Transactions Stored Procedures BY EXAMPLE: Triggers, Functions, Procedures, Cursors November 2014 Christos Skourlas
IMS 4212: Constraints & Triggers 1 Dr. Lawrence West, Management Dept., University of Central Florida Stored Procedures in SQL Server.
Program with PL/SQL Lesson 3. Interacting with the Oracle Server.
Kingdom of Saudi Arabia Ministry of Higher Education Al-Imam Muhammad Ibn Saud Islamic University College of Computer and Information Sciences Overview.
MySQL Tutorial. Databases A database is a container that groups together a series of tables within a single structure Each database can contain 1 or more.
1 Section 10 - Embedded SQL u Many computer languages allow you to embed SQL statements within the code (e.g. COBOL, PowerBuilder, C++, PL/SQL, etc.) u.
CS422 Principles of Database Systems Stored Procedures and Triggers Chengyu Sun California State University, Los Angeles.
1 Copyright © 2004, Oracle. All rights reserved. PL/SQL Programming Concepts: Review.
Chapter 5 Introduction to SQL.
PL/SQL.
Error Handling Summary of the next few pages: Error Handling Cursors.
Chapter 4: Introduction to PL/SQL
Chapter 2 Handling Data in PL/SQL Blocks Oracle9i Developer:
Database systems Lecture 3 – SQL + CRUD
Chapter 8 Advanced SQL.
Information Management
Stored Procedure Language
Presentation transcript:

1 Stored Procedures in MySQL Part I

2 Objectives SQL Vs. MySQL SP MySQL SP Parameters MySQL SP Control Structures

SQL Vs. MySQL SP SQL –No Procedural Capability –Time Consuming Processing –No Error Handling Procedures –No Sharing of code –Low performance

SQL Vs. MySQL SP MySQL SP –Highly structured, readable, and accessible –Error Handling Procedures –Facilitate Sharing of code –Improved Transaction Performance –Portable and standard Code

5 First MySQL SP DELIMITER$$ DROP PROCEDURE IF EXIST HelloWorld()$$ CREATE PROCEDURE HelloWorld() BEGIN SELECT “Hello World”; END$$ DELIMITER ; mysql> CALL HelloWorld(); | Hello World | | Hello World | row in set (0.01 sec) Query OK, 0 rows affected (0.01 sec)

6 Parameters CREATE PROCEDURE p5 ()... CREATE PROCEDURE p5 ([IN] name data-type)... CREATE PROCEDURE p5 (OUT name data-type)... CREATE PROCEDURE p5 (INOUT name data-type)...

7 Parameters CREATE PROCEDURE p5(p INT) = p // mysql> CALL p5(12345)// Query OK, 0 rows affected (0.00 sec) mysql> | | |

8 Parameters mysql> CREATE PROCEDURE p6 (OUT p INT) -> SET p = -5 // mysql> CALL mysql> | | -5 |

9 Variables and Data Types Variables –Used to store numbers, character strings, dates, and other data values –Avoid using keywords, table names and column names as variable names –Must be declared with data type before use

10 Variable DECLARE varname DATA-TYPE DEFAULT defaultvalue; –DECLARE a, b INT DEFAULT 5; –DECLARE str VARCHAR(50); –DECLARE today TIMESTAMP DEFAULT CURRENT_DATE; –DECLARE v1, v2, v3 FLOAT;

11 Variable CREATE PROCEDURE p8 () BEGIN DECLARE a INT; DECLARE b INT; SET a = 5; INSERT INTO t VALUES (a); SELECT s1 * a INTO b FROM t WHERE s1 = 10; SELECT b; END; //

12 Working with Variables DELIMITER // CREATE PROCEDURE `var_proc` (IN paramstr VARCHAR(20)) BEGIN DECLARE a, b INT DEFAULT 5; DECLARE str VARCHAR(50); DECLARE today TIMESTAMP DEFAULT CURRENT_DATE; DECLARE v1, v2, v3 TINYINT; INSERT INTO table1 VALUES (a); SELECT name, date into str, today FROM table2 WHERE b >=5; SELECT str, today; END //

13 Variable Scope CREATE PROCEDURE p11 () BEGIN DECLARE x1 CHAR(5) DEFAULT 'outer'; BEGIN DECLARE x1 CHAR(5) DEFAULT 'inner'; SELECT x1; END; SELECT x1; END; //

14 MySQL Decision Control Structures Use IF/ELSIF to evaluate many conditions: –IF condition1 THEN commands that execute if condition1 is TRUE; ELSIF condition2 THEN commands that execute if condition2 is TRUE; ELSIF condition3 THEN commands that execute if condition3 is TRUE;... ELSE commands that execute if none of the conditions are TRUE; END IF;

IF/ELSE Example DECLARE a, b INT; BEGIN SELECT e, f INTO a, b FROM T1 WHERE e>1; IF b=1 THEN INSERT INTO T1 VALUES(b,a); ELSE INSERT INTO T1 VALUES(b+10,a+10); END IF; END; / 15

IF/ELSIF Example 1... IF rating > 7 THEN SET v_message = 'You are great'; ELSIF rating >= 5 THEN SET v_message = 'Not bad'; ELSE SET v_message = 'Pretty bad'; END IF;...

CREATE PROCEDURE p12 (IN parameter1 INT) BEGIN DECLARE variable1 INT; SET variable1 = parameter1 + 1; IF variable1 = 0 THEN INSERT INTO t VALUES (17); END IF; IF parameter1 = 0 THEN UPDATE t SET s1 = s1 + 1; ELSE UPDATE t SET s1 = s1 + 2; END IF; END; //

18 Simple CASE Simple CASE statement condition on top CASE expression WHEN value THEN statements [WHEN value THEN statements...] [ELSE statements] END CASE;

19 Simple CASE CREATE PROCEDURE p13 (IN parameter1 INT) BEGIN DECLARE variable1 INT; SET variable1 = parameter1 + 1; CASE variable1 WHEN 0 THEN INSERT INTO t VALUES (17); WHEN 1 THEN INSERT INTO t VALUES (18); ELSE INSERT INTO t VALUES (19); END CASE; END; //

20 Searched CASE (IF) Searched CASE statement condition case by case (IF) CASE WHEN condition/expression THEN statements [WHEN condition/expression THEN statements...] [ELSE statements] END CASE;

21 Searched CASE (IF) CREATE PROCEDURE GetCustomerLevel( in p_customerNumber int(11), out p_customerLevel varchar(10)) BEGIN DECLARE creditlim double; SELECT creditlimit INTO creditlim FROM customers WHERE customerNumber = p_customerNumber; CASE WHEN creditlim > THEN SET p_customerLevel = 'PLATINUM'; WHEN (creditlim = 10000) THEN SET p_customerLevel = 'GOLD'; WHEN creditlim < THEN SET p_customerLevel = 'SILVER'; END CASE; END$$

22 Loops Program structure that executes a series of program statements, and periodically evaluates an exit condition to determine if the loop should repeat or exit Pretest loop: evaluates the exit condition before any program commands execute Posttest loop: executes one or more program commands before the loop evaluates the exit condition for the first time

Loops MySQL SP has 3 loop structures –LOOP … END LOOP; –WHILE … END WHILE; –REPEAT … END REPEAT; 23

24 The WHILE... END WHILE CREATE PROCEDURE p14 () BEGIN DECLARE v INT; SET v = 0; WHILE v < 5 DO INSERT INTO t VALUES (v); SET v = v + 1; END WHILE; END; //

25 The REPEAT...END REPEAT Loop CREATE PROCEDURE p15 () BEGIN DECLARE v INT; SET v = 0; REPEAT INSERT INTO t VALUES (v); SET v = v + 1; UNTIL v >= 5 END REPEAT; END; //

26 LOOP … END LOOP CREATE PROCEDURE p16 () BEGIN DECLARE v INT; SET v = 0; loop_label: LOOP INSERT INTO t VALUES (v); SET v = v + 1; IF v >= 5 THEN LEAVE loop_label; END IF; END LOOP; END; //

CREATE PROCEDURE p20 () BEGIN DECLARE v INT; SET v = 0; loop_label: LOOP IF v = 3 THEN SET v = v + 1; ITERATE loop_label; END IF; INSERT INTO t VALUES (v); SET v = v + 1; IF v >= 5 THEN LEAVE loop_label; END IF; END LOOP; END; //

28 Error Handlers Condition handlers –EXIT –CONTINUE DECLARE {CONTINUE | EXIT} HANDLER FOR {SQLSTATE sqlstate_code| MySQL errorcode| condition_name} handler_actions

29 Error Handlers DECLARE EXIT HANDLER FOR 1062 /* MySQL ERROR code Duplicate key*/ SET duplicate_key=1; INSERT INTO city (ID,name,CountryCode,Population) VALUES(in_ID,in_name,in_CountryCode,in_Pop); IF duplicate_key=1 THEN SELECT CONCAT('Failed to insert ',in_name, ': duplicate key') as "Result"; END IF;

30 Error Handlers CREATE PROCEDURE p24 () BEGIN DECLARE `Constraint Violation` CONDITION FOR SQLSTATE '23000'; DECLARE EXIT HANDLER FOR `Constraint Violation` ROLLBACK; START TRANSACTION; INSERT INTO t2 VALUES (1); COMMIT; END; //

31 Error Handlers CREATE TABLE t4 (s1 int,primary key(s1));// CREATE PROCEDURE p23 () BEGIN DECLARE CONTINUE HANDLER FOR SQLSTATE '23000' = 1; = 1; INSERT INTO t4 VALUES (1); = 2; INSERT INTO t4 VALUES (1); = 3; END;//

32 CREATE PROCEDURE AddOrderItem( in orderNo int) BEGIN DECLARE C INT; SELECT COUNT(orderNumber) INTO C FROM orders WHERE orderNumber = orderNo; -- check if orderNumber exists IF(C != 1) THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Order No not found in orders table'; END IF; -- more code below END; //

33 Cursors To handle a SELECT statement that returns more than one row Pointer to a memory location that the DBMS uses to process a SQL query Use to retrieve and manipulate database data In MySQL for now the CURSORS are forward ONLY.

34 Implicit Cursor

35 Using an Implicit Cursor Executing a SELECT query creates an implicit cursor To retrieve it into a variable use INTO: – SELECT field1, field2,... INTO variable1, variable2,... FROM table1, table2,... WHERE join_ conditions AND search_condition_to_retrieve_1_record; Can only be used with queries that return exactly one record

Using an Implicit Cursor BEGIN DECLARE v_sname VARCHAR(10); DECLARE v_rating INT; SELECTsname, rating INTOv_sname, v_rating FROMSailors WHEREsid = '112'; END; / INTO clause is required. Query must return exactly one row. Otherwise, a NO_DATA_FOUND or TOO_MANY_ROWS exception is thrown.

37 Explicit Cursor Use for queries that return multiple records or no records Must be explicitly declared and used

38 Using an Explicit Cursor DECLARE cursor-name CURSOR FOR SELECT...; OPEN cursor-name; FETCH cursor-name INTO variable [, variable]; CLOSE cursor-name;

CREATE PROCEDURE p25 (OUT return_val INT) BEGIN DECLARE a,b INT; DECLARE cur_1 CURSOR FOR SELECT s1 FROM t; DECLARE CONTINUE HANDLER FOR NOT FOUND SET b = 1; OPEN cur_1; REPEAT FETCH cur_1 INTO a; UNTIL b = 1 END REPEAT; CLOSE cur_1; SET return_val = a; END;// Using an Explicit Cursor

40 Cursor Characteristics READ ONLY –Cannot update the cursor NOT SCROLLABLE –Cannot move back and forth ASENSITIVE –avoid doing updates on a table while you have a cursor open on the same table

41 Functions CREATE FUNCTION factorial (n DECIMAL(3,0)) RETURNS DECIMAL(20,0) BEGIN DECLARE factorial DECIMAL(20,0) DEFAULT 1; DECLARE counter DECIMAL(3,0); SET counter = n; REPEAT SET factorial = factorial * counter; SET counter = counter - 1; UNTIL counter = 1 END REPEAT; RETURN factorial; END //

Triggers Triggers are special procedures which we want activated when someone has performed some action on the DB. For example, we might define a trigger that is executed when someone attempts to insert a row into a table, and the trigger checks that the inserted data is valid.

Triggers There are four types of database triggers: –Table-level triggers can initiate activity before or after an INSERT, UPDATE, or DELETE event. –View-level triggers defines what can be done to the view. –Database-level triggers can be activated at startup and shutdown of a database. –Session-level triggers can be used to store specific information. 43

Triggers CREATE [DEFINER = { user|CURRENT_USER }] TRIGGER trigger_name {BEFORE|AFTER} {UPDATE|INSERT|DELETE} ON table_name FOR EACH ROW trigger_statements

45 CREATE TRIGGER nameInUppercase BEFORE INSERT ON city FOR EACH ROW BEGIN DECLARE dummy INT; IF ISNULL(NEW.Name)<1 THEN SET NEW.Name=FirstToUppercase(NEW.Name); END IF; END$$ insert into city (Name) values ('adamo'); [world]> Select Name from city where Name like "Ad%" Order by name limit 1; | Name | | Adamo | row in set (0.00 sec)

46 CREATE TRIGGER example_before_insert_allow_only_one_active BEFORE INSERT ON example_tbl FOR EACH ROW BEGIN IF NEW.active = 1 AND (SELECT COUNT(id) FROM example_tbl WHERE active=1 AND foreign_key_id=NEW.foreign_key_id) > 0 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Cannot add or update row: only one active row allowed per type'; END IF; END; // Triggers

47 CREATE TRIGGER example_before_update_allow_only_one_active BEFORE UPDATE ON example_tbl FOR EACH ROW BEGIN IF NEW.active = 1 AND (SELECT COUNT(id) FROM example_tbl WHERE id<>NEW.id AND active=1 AND foreign_key_id=NEW.foreign_key_id) > 0 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Cannot add or update row: only one active row allowed per type'; END IF; END; // Triggers