You are on page 1of 30

Hệ quản trị cơ sở dữ liệu

Stored procedure

Dư Phương Hạnh
Bộ môn Hệ thống thông tin
Khoa CNTT, trường Đại học Công nghệ
Đại học Quốc gia Hanoi

hanhdp@vnu.edu.vn
Outline
 Introduction
 Create Stored procedure
 Variables, parameters and others
 Exercises

Tài liệu tham khảo:


http://www.mysqltutorial.org/mysql-stored-proce
dure-tutorial.aspx

2 Hệ quản trị CSDL @ BM HTTT


Introduction
 By definition, stored procedure (sp) is a segment of
declarative SQL code which is stored in the database
catalog and can be invoked later by a program, a
trigger or even a stored procedure.
 Almost RDMBS supports recursive stored procedure
but MySQL does not support it well. Check your version
of MySQL before using recursive stored procedure.
 Mysql did not support stored procedure, trigger, event…
until version 5.0. Those features has been added to
MySQL database engine to allow MySQL to be more
flexible and powerful. 

3 Hệ quản trị CSDL @ BM HTTT


Advantages
 Increases performance of application. Once
created, it is compiled and stored in the database
catalog. It runs faster than uncompiled SQL
commands which are sent from application.
 Reduced the traffic between application and
database server because instead of sending
multiple uncompiled lengthy SQL commands
statements, application only has to send the stored
procedure name and get the data back to
manipulate it futher.

4 Hệ quản trị CSDL @ BM HTTT


Advantages
 It is reusable and transparent to any application
which wants to use it. Stored procedure exposes the
database interface to all applications so developers
don't have to program the functions which are
already supported instored procedure in all external
applications.
 It is secured. Database administrator can grant the
access right to application which wants to access
stored procedures in database catalog without
granting any permission on the underlying database
tables.

5 Hệ quản trị CSDL @ BM HTTT


Disadvantages
 Sp make the database server high load in both
memory and processors. Instead of being focused
on the storing and retrieving data, you could be
asking the database server to perform a number of
logical operations or a complex of business logic
which is not the well designed in database server.
 It only contains declarative SQL so it is very difficult
to write a procedure with complexity of business
logic like other languages in application layer such
as Java, C#, C++…

6 Hệ quản trị CSDL @ BM HTTT


Disadvantages
 You cannot debug stored procedure in almost
RDMBSs and in MySQL also. There are some
workarounds on this problem but it still not good
enough to do so.
 Writing and maintaining stored procedure usually
required specialized skill set that not all developers
possess. This introduced the problem in both
application development and maintain phase.

7 Hệ quản trị CSDL @ BM HTTT


Create SP
DELIMITER //
CREATE PROCEDURE sp_name

BEGIN

SELECT * FROM products;

END //
DELIMITER ;

CALL sp_name()

8 Hệ quản trị CSDL @ BM HTTT


Hệ quản trị cơ sở dữ liệu

Programming with SP

Dư Phương Hạnh
Bộ môn Hệ thống thông tin
Khoa CNTT, trường Đại học Công nghệ
Đại học Quốc gia Hanoi

hanhdp@vnu.edu.vn
Variables
 Declaring variables
– DECLARE variable_name datatype(size) DEFAULT default_value;
 Assigning variables
– DECLARE total_count INT DEFAULT 0 ;
SET total_count = 10;
– DECLARE total_products INT DEFAULT 0;
SELECT COUNT(*) INTO total_products
FROM products;

10 Hệ quản trị CSDL @ BM HTTT


Variables
 Variables scope
– If you declare a variable inside a stored procedure, it will
be out of scope when the END of stored procedure
reached.
– If you defined a variable inside block BEGIN/END inside a
stored procedure it will be out of scope if the END
reached. You can declare two variables or more variables
with the same name in different scopes; the variable only
is effective in its scope.
– A variable with the ‘@’ at the beginning is session
variable. It exists until the session end.

11 Hệ quản trị CSDL @ BM HTTT


Parameters
 MODE param_name param_type(param_size)

 Almost stored procedures you develop require parameters to


make the it more flexible and useful. In MySQL, a parameter
has one of three modes: IN, OUT and INOUT.
– IN: the default mode. IN indicates that a parameter can be passed
into stored procedures but any modification inside stored
procedure does not change parameter.
– OUT: indicates that stored procedure can change this parameter and
pass back to the calling program.
– INOUT: obviously this mode is combined of IN and OUT mode; you
can pass parameter into stored procedure and get it back with the
new value from calling program.

12 Hệ quản trị CSDL @ BM HTTT


Parameters
DELIMITER $$
CREATE PROCEDURE GetOfficeByCountry(IN
countryName VARCHAR(255))
BEGIN
SELECT city, phone
FROM offices
WHERE country = countryName;
END $$
DELIMITER ;
CALL GetOfficeByCountry('USA') 
13 Hệ quản trị CSDL @ BM HTTT
Parameters
DELIMITER $$
CREATE PROCEDURE CountOrderByStatus(
IN orderStatus VARCHAR(25), OUT total INT)
BEGIN
SELECT count(orderNumber) INTO total
FROM orders
WHERE status = orderStatus;
END$$
DELIMITER ;

14 Hệ quản trị CSDL @ BM HTTT


Parameters
 So to get number of shipped orders, we just perform
following statements

CALL CountOrderByStatus('Shipped',@total);

 To get number of orders in process we do the same as


above

CALL CountOrderByStatus('in process',@total);


SELECT @total AS total_in_process;

15 Hệ quản trị CSDL @ BM HTTT


Parameters
DELIMITER $$
CREATE PROCEDURE Capitalize(INOUT str VARCHAR(1024))
BEGIN
DECLARE i INT DEFAULT 1;
DECLARE myc, pc CHAR(1);
DECLARE outstr VARCHAR(1000) DEFAULT str;
WHILE i <= CHAR_LENGTH(str) DO
SET myc = SUBSTRING(str, i, 1);
SET pc = CASE WHEN i = 1 THEN ' '
ELSE SUBSTRING(str, i - 1, 1)
END;
IF pc IN (' ', '&', '''', '_', '?', ';', ':', '!', ',', '-', '/', '(', '.') THEN
SET outstr = INSERT(outstr, i, 1, UPPER(myc));
END IF;
SET i = i + 1;
END WHILE;
SET str = outstr;
END$$
DELIMITER ;

16 Hệ quản trị CSDL @ BM HTTT


Parameters
Using Capitalize stored procedure:

SET @str = 'mysql stored procedure tutorial';


CALL Capitalize(@str);
SELECT @str;

17 Hệ quản trị CSDL @ BM HTTT


Conditional Control
MySQL supports two conditional control statement such as IF
and CASE.
IF expression THEN commands
[ELSEIF expression THEN commands]
[ELSE commands]
END IF;
CASE
WHEN expression THEN commands

WHEN expression THEN commands
ELSE commands
END CASE;
18 Hệ quản trị CSDL @ BM HTTT
Loop
 WHILE
WHILE expression DO
Statements
END WHILE

 REPEAT
REPEAT
Statements;
UNTIL expression
END REPEAT

 LOOP, LEAVE and ITERATE

19 Hệ quản trị CSDL @ BM HTTT


Loop
DELIMITER $$
CREATE PROCEDURE LoopProc()
BEGIN
DECLARE x INT; DECLARE str VARCHAR(255);
SET x = 1; SET str = '';
loop_label: LOOP
IF x > 10 THEN LEAVE loop_label; END IF;
SET x = x + 1;
IF (x mod 2) THEN ITERATE loop_label;
ELSE SET str = CONCAT(str,x,',');
END IF;
END LOOP;
SELECT str;
END$$
DELIMITER ;

20 Hệ quản trị CSDL @ BM HTTT


Cursor
 MySQL supports cursor in stored procedures, functions and
triggers.

 DECLARE cursor_name CURSOR FOR SELECT_statement
 OPEN cursor_name;
 FETCH cursor_name INTO variable list;
 CLOSE cursor_name;
 One of the most important point when working with cursor is
you should use a NOT FOUND handler to avoid raising a
fatal “no data to fetch” condition.

21 Hệ quản trị CSDL @ BM HTTT


Example
CREATE PROCEDURE curdemo() read_loop: LOOP
BEGIN FETCH cur1 INTO a, b;
DECLARE done INT DEFAULT FETCH cur2 INTO c;
FALSE; IF done THEN
DECLARE a CHAR(16); LEAVE read_loop;
END IF;
DECLARE b, c INT;
IF b < c THEN
DECLARE cur1 CURSOR FOR
INSERT INTO test.t3 VALUES (a,b);
SELECT id,data
ELSE
FROM test.t1;
INSERT INTO test.t3 VALUES (a,c);
DECLARE cur2 CURSOR FOR END IF;
SELECT i FROM test.t2;
END LOOP;
DECLARE CONTINUE HANDLER
FOR NOT FOUND
CLOSE cur1;
SET done = TRUE; CLOSE cur2;
OPEN cur1; END;
OPEN cur2;

22 Hệ quản trị CSDL @ BM HTTT


Handler
 DECLARE type HANDLER FOR condition1,
condition2, condition3, ... statement;
 condition_name
– SQLWARNING: Matches any SQLSTATE that begins with
01.
– NOT FOUND: Matches any SQLSTATE that begins with 02.
– SQLEXCEPTION:
 handler_type:
– CONTINUE
– EXIT
– UNDO

23 Hệ quản trị CSDL @ BM HTTT


Handler
 DECLARE type HANDLER FOR condition1,
condition2, condition3, ... statement;

CREATE FUNCTION order_of_customer(customer_id INT)


RETURNS INT
READS SQL DATA
BEGIN
DECLARE Order_id INT;
DECLARE EXIT HANDLER FOR NOT FOUND RETURN NULL;
SELECT OrderNumber INTO Order_id
FROM Order
WHERE CustomerNumber = customer_id;
RETURN Order_id;

24 Hệ quản trị CSDL @ BM HTTT


Managing SP
 DROP SP
DROP {PROCEDURE | FUNCTION} [IF EXISTS]
sp_name

 ALTER SP
ALTER PROCEDURE proc_name [characteristic ...]

We cannot change the parameters or body of a stored


procedure; to make such changes, you must drop
and re-create the procedure.

25 Hệ quản trị CSDL @ BM HTTT


Exercises
1. Viết stored procedure trả về kết quả là tên mặt hàng bán chạy nhất giữa
hai mốc thời gian, sử dụng 2 tham số vào là hai mốc thời gian; tham số
trả lại là tên mặt hàng bán chạy nhất.

2.Viết stored procedure trả về


kết quả là tên khách hàng có
tổng tiền mua hàng nhiều
nhất giữa hai mốc thời gian.

26 Hệ quản trị CSDL @ BM HTTT


Exercises
2. Viết một stored procedure thực hiện công việc sau: Đưa ra
thông tin về Ngày đặt hàng, Ngày yêu cầu nhận hàng, Ngày
đơn hàng được đáp ứng; sử dụng hai tham số Mã đơn hàng và
mã khách hàng.
-Nếu tham số Mã đơn hàng nhận giá trị 0 thì đưa ra thông tin
như trên, tương ứng với mã khách hàng được cung cấp.
-Nếu tham số Mã khách hàng nhận giá trị 0 thì đưa ra thông tin
như trên, tương ứng với mã đơn hàng được cung cấp.
- Nếu cả hai tham số nhận giá trị khác 0:
- Nếu ngày đơn hàng được đáp ứng trùng với ngày yêu cầu nhận
hàng thì đưa ra thông báo ‘Đáp ứng tốt’; ngược lại thì thông báo ‘Đáp
ứng chậm’
- Nếu không tìm được thông tin tương ứng thì thông báo ‘Không có
thông tin’
27 Hệ quản trị CSDL @ BM HTTT
Hệ quản trị cơ sở dữ liệu

Function

Dư Phương Hạnh
Bộ môn Hệ thống thông tin
Khoa CNTT, trường Đại học Công nghệ
Đại học Quốc gia Hanoi

hanhdp@vnu.edu.vn
Function vs Stored Procedure
Procedure Function
Execute CALL statement SQL statement: Select,
update…
Return value One or more values can Only on value returned by
be return RETURN statement
Parameters IN, OUT, INOUT Only in-parameter
Using proc/function A proc can use other procs Only use other functions
or functions inside it. inside it.

29 Hệ quản trị CSDL @ BM HTTT


Function vs Procedure
CREATE FUNCTION name ([parameterlist])
RETURNS datatype [options]
sqlcode

DROP FUNCTION [IF EXISTS] name

30 Hệ quản trị CSDL @ BM HTTT

You might also like