MYSQL Stored procedures, functions, and triggers
MySQL supports stored procedures, functions, and triggers as part of its database management system. These database objects are used to encapsulate and manage logic and actions within the database. Let's explore each of them in more detail:
Stored Procedures:
Purpose: Stored procedures are a collection of one or more SQL statements that are stored on the database server and can be executed as a single unit. They are typically used for performing tasks that involve multiple SQL statements and need to be executed repeatedly.
Syntax for Creating a Stored Procedure:
sql code
CREATE PROCEDURE procedure_name(parameters)
BEGIN
-- SQL statements
END;
Example:
sql code
DELIMITER //
CREATE PROCEDURE GetCustomerOrders(IN customerID INT)
BEGIN
SELECT * FROM orders WHERE customer_id = customerID;
END //
DELIMITER ;
Execution:
sql code
CALL GetCustomerOrders(123);
Stored Functions:
Purpose: Stored functions are similar to stored procedures, but they return a single value. They are commonly used to encapsulate logic and calculations that return a specific result.
Syntax for Creating a Stored Function:
sql code
CREATE FUNCTION function_name(parameters) RETURNS data_type
BEGIN
-- SQL statements
RETURN result;
END;
Example:
sql code
DELIMITER //
CREATE FUNCTION CalculateTotalPrice(orderID INT) RETURNS DECIMAL(10, 2)
BEGIN
DECLARE total DECIMAL(10, 2);
SELECT SUM(price) INTO total FROM order_items WHERE order_id = orderID;
RETURN total;
END //
DELIMITER ;
Execution:
sql code
SELECT CalculateTotalPrice(456);
Triggers:
Purpose: Triggers are special types of stored procedures that are automatically executed when a specific event occurs in the database. These events can be INSERT, UPDATE, DELETE, etc. Triggers are often used to enforce data integrity rules or perform auditing tasks.
Syntax for Creating a Trigger:
sql code
CREATE TRIGGER trigger_name
{BEFORE | AFTER} {INSERT | UPDATE | DELETE} ON table_name
FOR EACH ROW
BEGIN
-- SQL statements
END;
Example:
sql code
DELIMITER //
CREATE TRIGGER AfterOrderInsert
AFTER INSERT ON orders
FOR EACH ROW
BEGIN
INSERT INTO order_log (order_id, action, timestamp)
VALUES (NEW.id, 'INSERT', NOW());
END //
DELIMITER ;
These are essential database objects for managing and controlling the behavior of your MySQL database. Stored procedures and functions are used to encapsulate reusable logic, while triggers are used to respond to specific events automatically.
Comments
Post a Comment