SQL Stored Procedure
A stored procedure is a collection of pre-compiled SQL statements stored inside the
database. It is a subroutine or a subprogram in the regular computing language. A
procedure always contains a name, parameter lists, and SQL statements.
Syntax:
DELIMITER &&
CREATE PROCEDURE procedure_name [[IN | OUT | INOUT] parameter_name
datatype [, parameter datatype]) ]
BEGIN
Declaration_section
Executable_section
END &&
DELIMITER ;
Parameter Types:
1. IN parameter
It is the default mode. It takes a parameter as input, such as an attribute.
When we define it, the calling program has to pass an argument to the stored
procedure.
2. OUT parameters
It is used to pass a parameter as output. Its value can be changed inside the
stored procedure, and the changed (new) value is passed back to the calling
program.
3. INOUT parameters
It is a combination of IN and OUT parameters. It means the calling program
can pass the argument, and the procedure can modify the INOUT parameter,
and then passes the new value back to the calling program.
How to call a stored procedure?
We can use the CALL statement to call a stored procedure. This statement returns
the values to its caller through its parameters (IN, OUT, or INOUT). The following
syntax is used to call the stored procedure in MySQL:
CALL procedure_name ( parameter(s))
Create the tables given below and insert
some records
Patients Doctor
column_name data_type column_name data_type
patient_id int doctor_id int
name varchar name varchar
age int age int
gender varchar gender varchar
address varchar address varchar
disease varchar
doctor_id int
Bills Laboratory
column_name data_type column_name data_type
bill_no int lab_no int
patient_id int patient_id int
doctor_id int doctor_id int
room_charge int date date
no_of_days int amount int
Procedure without Parameter
Let’s create a stored procedure to extract the patient names that are
females.
Output:
Procedures with IN Parameter
Let’s create a stored procedure to extract the top ‘n’ doctor details in
descending order of age and ascending order of doctor name. ‘n’ is a
user input.
Output:
Procedures with multiple IN Parameter
Let’s create a stored procedure to insert a record in the patients table.
Output:
Procedures with OUT Parameter
Let’s create a stored procedure to extract and display the maximum
room charge taken.
Output:
Procedures with INOUT Parameter
Let’s create a stored procedure to extract the amount of laboratory bill in
‘var1’ and display the amount given by patient of patient id ‘var1’.
DROP the stored procedure