Stored Procedure and Function 21-05-2024
Stored Procedure and Function 21-05-2024
• STORED PROCEDURE
• FUNCTIONS(USER DEFINED)
STORED PROCEDURE
DELIMITER &&
CREATE PROCEDURE procedure_name [[IN | OUT | INOUT] paramet
er_name datatype [, parameter datatype]) ]
BEGIN
Declaration_section
Executable_section
END &&
DELIMITER ;
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.
Each parameter is assigned a name, a data type, and
direction like Input, Output, or Return. If a direction is not
specified, then by default, it is Input.
DELIMITER $$
CREATE PROCEDURE PROCEDURE_NAME( IN PARAMETER)
BEGIN
….
END$$
DELIMITER;
CALL procedure_name ( parameter(s))
OUT Parameters
The OUTPUT parameter is used when you want to
return some value from the stored procedure.
DELIMITER //
CREATE PROCEDURE PROCEDURE_NAME(OUT PARAMETER)
BEGIN
SELECT…INTO
END //
DELIMITER ;
When you want to pass in an initial value,update the value in the function and return
its updated value.
DELIMITER //
CRETE PROCEDURE PROCEDURE_NAME(INOUT PARAMETER)
BEGIN
SELCT..INTO…
END //
DELIMITER ;
MySQL Stored Function
A stored function in MySQL is a set of SQL statements that perform some
task/operation and return a single value. It is one of the types of stored
programs in MySQL.
DELIMITER //
CREATE FUNCTION FUNCTION_NAME(PARAMETER DATATYPE)
RETURNS DATATYPE
BEGIN
DECLARE VARIABLE_NAME DATATYPE
SELECT…;
RETURN VARIABLE_NAME;
END //
DELIMITER;
The function parameter may contain only the IN parameter but can't allow specifying this parameter
1.Return Value:
1. Function: Always returns a single value, either a scalar or a table.
2. Stored Procedure: Can return zero, single, or multiple values.
2.Parameters:
1. Function: Allows only input parameters and does not allow output parameters.
2. Stored Procedure: Allows both input and output parameters.
3.Statements Allowed:
1. Function: Only SELECT statements; DML statements like UPDATE and INSERT are not
allowed.
2. Stored Procedure: Can perform any operation on database objects, including SELECT
and DML statements.
4.Calling from Other Objects:
1. Function: Can be called from a SELECT statement.
2. Stored Procedure: Cannot be called from a SELECT/WHERE or HAVING statement
directly; an EXECUTE statement must be used.
MySQL Variables