Introducing Stored Procedures and Functions
Introducing Stored Procedures and Functions
and Functions
Definitions and Examples
Presented by: Tejus
What Are Stored Procedures?
• Definition:
• A stored procedure is a set of SQL statements
that can be stored in the database and
executed repeatedly, like a program.
• Features:
• - Encapsulation of SQL logic
• - Can accept input parameters
• - Improve performance by reducing
Example of a Stored Procedure
• Code Example:
• CREATE PROCEDURE GetCustomerDetails (IN
customerID INT)
• BEGIN
• SELECT * FROM Customers WHERE ID =
customerID;
• END;
• Explanation:
What Are Functions?
• Definition:
• A function is a database object that performs
a specific task and returns a single value.
• Features:
• - Always returns a value
• - Can be used in SQL queries
• - Helps modularize and reuse code
Example of a Function
• Code Example:
• CREATE FUNCTION CalculateDiscount(price
DECIMAL, discountRate DECIMAL)
• RETURNS DECIMAL
• BEGIN
• RETURN price * (1 - discountRate);
• END;
• Explanation:
Key Differences
• Aspect | Stored Procedure |
Function
• ---------------------|-----------------------------|--------
----------------
• Returns a value | Optional |
Mandatory
• Usage in queries | Cannot be used in SELECT
| Can be used in SELECT
• Transaction support | Supports transactions
| Cannot start transactions
Use Cases
• Stored Procedures:
• - Batch processing
• - Data validation before insert/update
• Functions:
• - Calculations
• - String or date manipulation
Advantages
• Stored Procedures:
• - Improved performance
• - Enhanced security
• Functions:
• - Simplified query writing
• - Reusability
Conclusion
• - Stored procedures and functions simplify
database operations by encapsulating logic
into reusable code blocks.
• - Choosing the right tool depends on the
specific use case.
Q&A
• Thank you for your attention!
• Questions are welcome.