MIT 213_Data Management_Tutorial 08
MIT 213_Data Management_Tutorial 08
1 Introduction
In the realm of data management, Structured Query Language (SQL) serves as a foundational
tool for interacting with databases. As databases evolve to accommodate complex applications,
advanced database operations become essential for ensuring efficiency, reliability, and
maintainability. This overview focuses on two critical areas: working with stored procedures,
functions, and triggers, and handling exceptions and errors in SQL.
1.1 Working with Stored Procedures, Functions, and Triggers
Stored procedures and functions encapsulate SQL code, allowing for reusable and modular
programming. A stored procedure is a set of SQL statements that can be executed as a single
unit, enabling developers to perform complex operations without needing to rewrite code.
Functions, on the other hand, return a single value and can be used within SQL statements,
enhancing the flexibility of queries.
Triggers are automated responses to specific events on a table, such as INSERT, UPDATE, or
DELETE operations. They help maintain data integrity and enforce business rules by executing
predefined actions in reaction to database changes. Understanding how to effectively create
and manage these elements is crucial for optimizing database performance and ensuring
consistent application behaviour.
1.2 Handling Exceptions and Errors in SQL
Despite robust planning and execution, errors can still occur during database operations.
Handling exceptions and errors in SQL is vital for maintaining the integrity of applications and
providing a seamless user experience. SQL offers various mechanisms for error handling,
allowing developers to anticipate potential issues and respond appropriately.
By employing structured exception handling, developers can catch and manage errors without
disrupting the flow of the application. This includes logging errors for analysis, rolling back
transactions to preserve data consistency, and providing informative feedback to users. Mastery
of these techniques is essential for building resilient database applications that can gracefully
manage unexpected situations.
In summary, advanced database operations involving stored procedures, functions, triggers,
and robust error handling are crucial for effective data management using SQL. These
techniques empower developers to create efficient, responsive, and reliable database
applications, ultimately enhancing the overall functionality and user experience of the systems
they support.
DELIMITER ;
2.2.3 Executing the Stored Procedure
To execute the AddBook procedure, you would call it with the required parameters:
CALL AddBook('Brave New World', 'Aldous Huxley', 9.99, 8);
This command will insert a new book into the Books table with the specified details.
DELIMITER //
RETURN total;
END //
DELIMITER ;
2.3.3 Using the Function
You can use the GetTotalPrice function in a SQL statement to calculate the total price for a
specific book and quantity:
SELECT GetTotalPrice(1, 3) AS TotalPrice; -- Calculates total price for 3
copies of "The Great Gatsby"
2.4 Working with Triggers
2.4.1 Definition and Purpose
Triggers are special types of stored procedures that automatically execute in response to certain
events on a table, such as INSERT, UPDATE, or DELETE. They are useful for enforcing
business rules and maintaining data integrity.
2.4.2 Creating a Trigger
Let’s create a trigger that updates the stock quantity in the Books table whenever a sale is made
in the Sales table.
DELIMITER //
-- Start a transaction
START TRANSACTION;
DELIMITER ;
3.2.2 Executing the Stored Procedure
Now, let's see how this procedure behaves in different scenarios.
3.2.2.1 Successful Sale:
CALL ProcessSale(1, 2); -- This should succeed if stock is sufficient
3.2.2.2 Sale with Insufficient Stock:
CALL ProcessSale(1, 10); -- This should trigger an error and roll back the
transaction
3.3 Error Messages
When the second call is executed, the procedure will catch the error and return:
An error occurred. The sale could not be processed.
3.4 Logging Errors
In larger applications, it is often beneficial to log errors for further analysis. This can be
achieved by creating an error log table.
3.5 Creating an Error Log Table
CREATE TABLE ErrorLog (
ErrorID INT AUTO_INCREMENT PRIMARY KEY,
ErrorMessage VARCHAR(255),
ErrorDate DATETIME
);
3.6 Modifying the Error Handler to Log Errors
We can modify the EXIT HANDLER in our stored procedure to log errors into the ErrorLog
table:
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
-- Log the error message
INSERT INTO ErrorLog (ErrorMessage, ErrorDate)
VALUES (CONCAT('Error processing sale for BookID: ', p_BookID), NOW());