Stored procedure, in the context of regular computing language, may be defined as a subroutine like a subprogram that is stored in a database. In the context of MySQL, it is a segment of declarative SQL statements stored inside the database catalog. Before writing stored procedures in MySQL, we must have to check the version because MySQL 5 introduces stored procedure. Following is the syntax for creating a stored procedure −
Syntax
CREATE [DEFINER = { user | CURRENT_USER }]
PROCEDURE sp_name ([proc_parameter[,...]])
[characteristic ...] routine_body
proc_parameter: [ IN | OUT | INOUT ] param_name type
type:
Any valid MySQL data type
characteristic:
COMMENT 'string'
| LANGUAGE SQL
| [NOT] DETERMINISTIC
| { CONTAINS SQL | NO SQL | READS SQL DATA
| MODIFIES SQL DATA }
| SQL SECURITY { DEFINER | INVOKER }
routine_body:
Valid SQL routine statementExample
Following is an example in which we created a simple procedure to get all the records from the table ‘student_info’ which have the following data −
mysql> select * from student_info; +-----+---------+------------+------------+ | id | Name | Address | Subject | +-----+---------+------------+------------+ | 100 | Aarav | Delhi | Computers | | 101 | YashPal | Amritsar | History | | 105 | Gaurav | Jaipur | Literature | | 110 | Rahul | Chandigarh | History | +------+--------+------------+------------+ 4 rows in set (0.00 sec)
Now, with the help of following queries we created the stored procedure named allrecords()
mysql> Delimiter // mysql> Create Procedure allrecords() -> BEGIN -> Select * from Student_info; -> END// Query OK, 0 rows affected (0.02 sec) mysql> DELIMITER ;