Create Stored Procedure In MySQL

A stored procedure in a relational database is a collection of SQL statements that are saved on the database server and executed on the server itself. Any SQL query including Insert, Update, Delete can be a part of a stored procedure. Stored procedures are secure way to access and manipulate data. Stored procedures also provide high performance results compare to embedded SQL queries in your code.
In this blog, let's see how to create a stored procedure in MySQL database.
Syntax to create a stored Procedure: 
  1. CREATE  
  2. [DEFINER = { user | CURRENT_USER }]  
  3. PROCEDURE sp_name ([proc_parameter[,...]])  
  4. [characteristic ...] routine_body  
Let's look at this in step by step.
Step 1: Create a Table 
  1. CREATE TABLE `employees` (  
  2. `id` int(11) NOT NULL AUTO_INCREMENT,  
  3. `employeeNumber` int(11) NOT NULL,  
  4. `lastname` varchar(50) NOT NULL,  
  5. PRIMARY KEY (`id`)  
  6. )
Step 2: For insertion create a stored procedure: 
  1. delimiter $$  
  2. CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_inser`  
  3. (IN `employeenum` int  
  4. IN `lastname` varchar(200)  
  5. )  
  6. begin  
  7. insert into employees (employeeNumber,lastname) values(employeenum,lastname);  
  8. END$$  
Step 3: Call stored procedure 
  1. call sp_inser(123,'rajeev')  
Learn more details on stored procedures here, Learn Everything About Stored Procedures In SQL Server