Stored procedures and triggers are database objects that can be used to extend the capabilities of a Database Management System (DBMS). They provide a way to encapsulate business logic, automate tasks, and enforce data integrity.
Stored Procedures:
-
Create a Stored Procedure:
- Use the
CREATE PROCEDURE
statement to define a stored procedure. It can include input parameters, output parameters, and a set of SQL statements.
- Use the
DELIMITER //
CREATE PROCEDURE sp_example(IN parameter1 INT, OUT result1 INT)
BEGIN
-- SQL statements
END //
DELIMITER ;
-
Call a Stored Procedure:
- Use the
CALL
statement to execute a stored procedure.
- Use the
CALL sp_example(1, @output);
-
Input and Output Parameters:
- Define input parameters using
IN
and output parameters usingOUT
. Parameters allow you to pass values into and out of the stored procedure.
- Define input parameters using
Triggers:
-
Create a Trigger:
- Use the
CREATE TRIGGER
statement to define a trigger. A trigger is associated with a specific table and is executed automatically when a specific event (e.g., INSERT, UPDATE, DELETE) occurs on that table.
- Use the
DELIMITER //
CREATE TRIGGER tr_example
AFTER INSERT ON table_name
FOR EACH ROW
BEGIN
-- SQL statements
END //
DELIMITER ;
-
Trigger Events:
- Specify the trigger event (INSERT, UPDATE, DELETE) and the timing (BEFORE or AFTER) using the
BEFORE
orAFTER
keywords.
- Specify the trigger event (INSERT, UPDATE, DELETE) and the timing (BEFORE or AFTER) using the
-
Accessing Old and New Values:
- Use
OLD
andNEW
to reference the old and new values in the trigger body. This is especially useful in UPDATE triggers.
- Use
CREATE TRIGGER tr_example
BEFORE UPDATE ON table_name
FOR EACH ROW
BEGIN
-- Access old and new values
SET @old_value = OLD.column_name;
SET @new_value = NEW.column_name;
END;
-
Enforce Data Integrity:
- Triggers can be used to enforce data integrity by performing additional checks or actions when certain conditions are met.
CREATE TRIGGER tr_check_balance
BEFORE INSERT ON transactions
FOR EACH ROW
BEGIN
IF NEW.amount > @account_balance THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'Insufficient funds';
END IF;
END;
-
Drop a Trigger:
- Use the
DROP TRIGGER
statement to remove a trigger from the database.
- Use the
DROP TRIGGER IF EXISTS tr_example;
Top comments (0)