Write a Procedure to Insert Data
In this step, you will learn how to create a stored procedure in MySQL that inserts data into a table. Stored procedures are precompiled SQL statements stored within the database. They can be executed by name, which can improve performance and security.
First, let's create a simple table to work with. Open your terminal and connect to the MySQL server using the following command:
mysql -u root -p
You will be prompted for the root password. Enter the password and press Enter.
Now, create a database named testdb
:
CREATE DATABASE IF NOT EXISTS testdb;
USE testdb;
Next, create a table named employees
with the following structure:
CREATE TABLE IF NOT EXISTS employees (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
department VARCHAR(255)
);
Now that we have a table, let's create a stored procedure to insert data into it. A stored procedure is created using the CREATE PROCEDURE
statement. We'll define a procedure named insert_employee
that inserts a new employee record.
Here's the SQL code for the stored procedure:
DELIMITER //
CREATE PROCEDURE insert_employee (IN employee_name VARCHAR(255), IN employee_department VARCHAR(255))
BEGIN
INSERT INTO employees (name, department) VALUES (employee_name, employee_department);
END //
DELIMITER ;
Let's break down this code:
DELIMITER //
: This changes the statement delimiter from ;
to //
. This is necessary because the procedure itself contains semicolons, and we need to tell MySQL to treat the entire procedure definition as a single statement.
CREATE PROCEDURE insert_employee
: This declares the creation of a stored procedure named insert_employee
.
(IN employee_name VARCHAR(255), IN employee_department VARCHAR(255))
: This defines the input parameters for the procedure. employee_name
and employee_department
are the names of the parameters, and VARCHAR(255)
is their data type. The IN
keyword indicates that these are input parameters.
BEGIN ... END
: This block contains the SQL statements that will be executed when the procedure is called.
INSERT INTO employees (name, department) VALUES (employee_name, employee_department);
: This is the SQL statement that inserts a new row into the employees
table, using the values passed in as input parameters.
DELIMITER ;
: This resets the statement delimiter back to ;
.
To execute this code, you can copy and paste it directly into your MySQL terminal.
After executing the code, you can verify that the procedure has been created by running the following command:
SHOW PROCEDURE STATUS WHERE db = 'testdb' AND name = 'insert_employee';
This command will display information about the insert_employee
procedure, including its name, database, and creation date.
You have now successfully created a stored procedure to insert data into the employees
table. In the next step, you will learn how to call this procedure.