Download presentation
Presentation is loading. Please wait.
Published byBrook Kennedy Modified over 9 years ago
1
1 Stored Procedures in MySQL Part I
2
2 Objectives SQL Vs. MySQL SP MySQL SP Parameters MySQL SP Control Structures
3
SQL Vs. MySQL SP SQL –No Procedural Capability –Time Consuming Processing –No Error Handling Procedures –No Sharing of code –Low performance
4
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
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 | +-------------+ 1 row in set (0.01 sec) Query OK, 0 rows affected (0.01 sec)
6
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
7 Parameters CREATE PROCEDURE p5(p INT) SET @x = p // mysql> CALL p5(12345)// Query OK, 0 rows affected (0.00 sec) mysql> SELECT @x// +-------+ | @x | +-------+ | 12345 | +-------+
8
8 Parameters mysql> CREATE PROCEDURE p6 (OUT p INT) -> SET p = -5 // mysql> CALL p6(@y)// mysql> SELECT @y// +------+ | @y | +------+ | -5 | +------+
9
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
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
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
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
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
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;
15
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
16
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;...
17
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
18 Simple CASE Simple CASE statement condition on top CASE expression WHEN value THEN statements [WHEN value THEN statements...] [ELSE statements] END CASE;
19
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
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
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 > 50000 THEN SET p_customerLevel = 'PLATINUM'; WHEN (creditlim = 10000) THEN SET p_customerLevel = 'GOLD'; WHEN creditlim < 10000 THEN SET p_customerLevel = 'SILVER'; END CASE; END$$
22
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
23
Loops MySQL SP has 3 loop structures –LOOP … END LOOP; –WHILE … END WHILE; –REPEAT … END REPEAT; 23
24
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
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
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; //
27
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
28 Error Handlers Condition handlers –EXIT –CONTINUE DECLARE {CONTINUE | EXIT} HANDLER FOR {SQLSTATE sqlstate_code| MySQL errorcode| condition_name} handler_actions
29
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
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
31 Error Handlers CREATE TABLE t4 (s1 int,primary key(s1));// CREATE PROCEDURE p23 () BEGIN DECLARE CONTINUE HANDLER FOR SQLSTATE '23000' SET @x = 1; SET @x = 1; INSERT INTO t4 VALUES (1); SET @x = 2; INSERT INTO t4 VALUES (1); SET @x = 3; END;//
32
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
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
34 Implicit Cursor
35
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
36
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
37 Explicit Cursor Use for queries that return multiple records or no records Must be explicitly declared and used
38
38 Using an Explicit Cursor DECLARE cursor-name CURSOR FOR SELECT...; OPEN cursor-name; FETCH cursor-name INTO variable [, variable]; CLOSE cursor-name;
39
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
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
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 //
42
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.
43
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
44
Triggers CREATE [DEFINER = { user|CURRENT_USER }] TRIGGER trigger_name {BEFORE|AFTER} {UPDATE|INSERT|DELETE} ON table_name FOR EACH ROW trigger_statements
45
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'); tusa@localhost:3306 [world]> Select Name from city where Name like "Ad%" Order by name limit 1; +-------+ | Name | +-------+ | Adamo | +-------+ 1 row in set (0.00 sec)
46
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
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
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.