Professional Documents
Culture Documents
2 2-SPFunction
2 2-SPFunction
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
BEGIN
END //
DELIMITER ;
CALL sp_name()
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;
CALL CountOrderByStatus('Shipped',@total);
REPEAT
REPEAT
Statements;
UNTIL expression
END REPEAT
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.
ALTER SP
ALTER PROCEDURE proc_name [characteristic ...]
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.