0% found this document useful (0 votes)
3 views

DBMS__Lab_4_1___STORED_PROC

This lab exercise focuses on practical applications of MySQL Stored Procedures, guiding students through creating, executing, and managing them. It covers advanced features such as control structures, error handling, cursors, and dynamic SQL, with step-by-step instructions for setting up a database and performing various operations. The lab concludes with a comprehensive challenge to reinforce the concepts learned.

Uploaded by

cuong25mc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

DBMS__Lab_4_1___STORED_PROC

This lab exercise focuses on practical applications of MySQL Stored Procedures, guiding students through creating, executing, and managing them. It covers advanced features such as control structures, error handling, cursors, and dynamic SQL, with step-by-step instructions for setting up a database and performing various operations. The lab concludes with a comprehensive challenge to reinforce the concepts learned.

Uploaded by

cuong25mc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Lab 4.

1: Working with Stored Procedures in MySQL


Dr Hung Tran and Dr Tran Duc Minh

DATCOM Lab, Faculty of Data Science and Artificial Intelligence


College of Technology
National Economics University, Vietnam
Email: hung.tran@neu.edu.vn
Mobile: 086-646-4048

1
DATCOM Lab, Faculty of Data Science and Artificial Intelligence, NEU

Objective
This lab exercise is designed to guide students through the practical application of the concepts covered
in the MySQL Stored Procedures lecture. By the end of the lab, students will have hands-on experience
in creating, executing, managing, and optimizing stored procedures, including using advanced features
such as control structures, error handling, cursors, and dynamic SQL.

@DATCOM Lab 2
@DATCOM Lab

Lab Setup
Database Environment
• Database Name: lab stored procedures
• Tables: customers, orders, order items, products, error log

DATCOM Lab, Faculty of Data Science and Artificial Intelligence, NEU


• Sample Data: Provided below for each table.

Required Tools
• MySQL Workbench or any SQL editor that connects to your MySQL database.
• A text editor for writing and saving SQL scripts.

Step-by-Step Lab Exercises


Step 1: Setting Up the Database and Tables
3

Create the Database


CREATE DATABASE lab_stored_procedures;
USE lab_stored_procedures;

Create the customers Table


CREATE TABLE customers (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100),
type VARCHAR(10),
total_revenue DECIMAL(10,2)
);

Insert Sample Data into customers Table


INSERT INTO customers (name, email, type, total_revenue) VALUES
(’John Doe’, ’john.doe@example.com’, ’VIP’, 1000.00),
(’Jane Smith’, ’jane.smith@example.com’, ’Regular’, 500.00),
(’Alice Johnson’, ’alice.johnson@example.com’, ’VIP’, 1500.00),
(’Bob Brown’, ’bob.brown@example.com’, ’Regular’, 750.00);
@DATCOM Lab

Create the orders Table


CREATE TABLE orders (
id INT AUTO_INCREMENT PRIMARY KEY,
customer_id INT,
amount DECIMAL(10,2),
status VARCHAR(20),

DATCOM Lab, Faculty of Data Science and Artificial Intelligence, NEU


FOREIGN KEY (customer_id) REFERENCES customers(id)
);

Insert Sample Data into orders Table


INSERT INTO orders (customer_id, amount, status) VALUES
(1, 200.00, ’Pending’),
(2, 150.00, ’Processed’),
(3, 300.00, ’Pending’),
(4, 120.00, ’Processed’);

Create the order items Table


CREATE TABLE order_items (
id INT AUTO_INCREMENT PRIMARY KEY,
4

order_id INT,
product_id INT,
quantity INT,
price DECIMAL(10,2),
FOREIGN KEY (order_id) REFERENCES orders(id),
FOREIGN KEY (product_id) REFERENCES products(id)
);

Create the products Table


CREATE TABLE products (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
price DECIMAL(10,2)
);

Insert Sample Data into products Table


INSERT INTO products (name, price) VALUES
(’Laptop’, 800.00),
(’Smartphone’, 600.00),
@DATCOM Lab

(’Tablet’, 300.00),
(’Headphones’, 100.00);

Insert Sample Data into order items Table


INSERT INTO order_items (order_id, product_id, quantity, price) VALUES
(1, 1, 1, 800.00),

DATCOM Lab, Faculty of Data Science and Artificial Intelligence, NEU


(1, 4, 2, 100.00),
(2, 2, 1, 600.00),
(3, 3, 1, 300.00),
(4, 4, 1, 100.00);

Create the error log Table


CREATE TABLE error_log (
id INT AUTO_INCREMENT PRIMARY KEY,
order_id INT,
error_message VARCHAR(255),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
5

Step 2: Creating and Executing Simple Stored Procedures


Create a Simple Stored Procedure
DELIMITER $$
CREATE PROCEDURE GetAllCustomers()
BEGIN
SELECT * FROM customers;
END $$
DELIMITER ;

Execute the Stored Procedure


CALL GetAllCustomers();

Create a Stored Procedure with Parameters


DELIMITER $$
CREATE PROCEDURE GetCustomerByID(IN customer_id INT)
BEGIN
SELECT * FROM customers WHERE id = customer_id;
@DATCOM Lab

END $$
DELIMITER ;

Execute the Parameterized Stored Procedure


CALL GetCustomerByID(1); -- Replace 1 with any valid customer ID

DATCOM Lab, Faculty of Data Science and Artificial Intelligence, NEU


Step 3: Advanced Features of Stored Procedures
Declaring Variables and Using Control Structures
DELIMITER $$
CREATE PROCEDURE CalculateDiscount(IN customer_type VARCHAR(10), OUT discount DECIMAL(5,2))
BEGIN
IF customer_type = ’VIP’ THEN
SET discount = 0.20;
ELSE
SET discount = 0.05;
END IF;
END $$
6

DELIMITER ;

Execute the Procedure with Control Structures


CALL CalculateDiscount(’VIP’, @discount);
SELECT @discount;

CALL CalculateDiscount(’Regular’, @discount);


SELECT @discount;

Implementing Error Handling


DELIMITER $$
CREATE PROCEDURE SafeDivision(IN numerator DECIMAL(10,2), IN denominator DECIMAL(10,2), OUT result DECIMAL(10,2))
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
SET result = NULL;
SELECT ’Error: Division by zero’;
END;

SET result = numerator / denominator;


@DATCOM Lab

END $$
DELIMITER ;

Test the Error Handling Procedure


CALL SafeDivision(10, 2, @result);
SELECT @result; -- Expected output: 5.00

DATCOM Lab, Faculty of Data Science and Artificial Intelligence, NEU


CALL SafeDivision(10, 0, @result);
SELECT @result; -- Expected output: NULL

Working with Cursors


DELIMITER $$
CREATE PROCEDURE ListVIPCustomers()
BEGIN
DECLARE done BOOLEAN DEFAULT FALSE;
DECLARE customer_id INT;
DECLARE customer_name VARCHAR(100);

DECLARE vip_cursor CURSOR FOR SELECT id, name FROM customers WHERE type = ’VIP’;
7

DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

OPEN vip_cursor;

read_loop: LOOP
FETCH vip_cursor INTO customer_id, customer_name;
IF done THEN
LEAVE read_loop;
END IF;
SELECT customer_id, customer_name;
END LOOP;

CLOSE vip_cursor;
END $$
DELIMITER ;

Execute the Cursor-Based Procedure


CALL ListVIPCustomers();
@DATCOM Lab

Step 4: Managing Stored Procedures


Modifying a Stored Procedure
-- Drop the existing procedure
DROP PROCEDURE IF EXISTS GetCustomerByID;

DATCOM Lab, Faculty of Data Science and Artificial Intelligence, NEU


-- Recreate the procedure with the new column
DELIMITER $$
CREATE PROCEDURE GetCustomerByID(IN customer_id INT)
BEGIN
SELECT id, name, email FROM customers WHERE id = customer_id;
END $$
DELIMITER ;

Dropping a Stored Procedure


DROP PROCEDURE IF EXISTS CalculateDiscount;

Managing Privileges
GRANT EXECUTE ON PROCEDURE lab_stored_procedures.GetAllCustomers TO ’student_user’@’localhost’;
8

Step 5: Implementing Dynamic SQL


Creating a Dynamic SQL Stored Procedure
DELIMITER $$
CREATE PROCEDURE DynamicQuery(IN table_name VARCHAR(64), IN column_name VARCHAR(64), OUT row_count INT)
BEGIN
SET @query = CONCAT(’SELECT COUNT(’, column_name, ’) INTO @row_count FROM ’, table_name);
PREPARE stmt FROM @query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET row_count = @row_count;
END $$
DELIMITER ;

Execute the Dynamic SQL Procedure


CALL DynamicQuery(’customers’, ’id’, @row_count);
SELECT @row_count; -- Expected output: The number of rows in the customers table
@DATCOM Lab

CALL DynamicQuery(’orders’, ’id’, @row_count);


SELECT @row_count; -- Expected output: The number of rows in the orders table

Step 6: Comprehensive Challenge

DATCOM Lab, Faculty of Data Science and Artificial Intelligence, NEU


Create a Complex Stored Procedure
DELIMITER $$
CREATE PROCEDURE ProcessOrders(IN order_id INT, IN customer_id INT, IN order_amount DECIMAL(10,2))
BEGIN
DECLARE customer_exists BOOLEAN DEFAULT FALSE;
DECLARE order_exists BOOLEAN DEFAULT FALSE;

DECLARE EXIT HANDLER FOR SQLEXCEPTION


BEGIN
ROLLBACK;
INSERT INTO error_log (order_id, error_message)
VALUES (order_id, ’Error processing order’);
END;
9

START TRANSACTION;

-- Validate customer
SELECT COUNT(*) INTO customer_exists FROM customers WHERE id = customer_id;
IF customer_exists = 0 THEN
SIGNAL SQLSTATE ’45000’ SET MESSAGE_TEXT = ’Customer does not exist.’;
END IF;

-- Validate order
SELECT COUNT(*) INTO order_exists FROM orders WHERE id = order_id;
IF order_exists > 0 THEN
SIGNAL SQLSTATE ’45000’ SET MESSAGE_TEXT = ’Order already exists.’;
END IF;

-- Insert the order


INSERT INTO orders (id, customer_id, amount) VALUES (order_id, customer_id, order_amount);

-- Update customer’s total revenue


UPDATE customers SET total_revenue = total_revenue + order_amount WHERE id = customer_id;
@DATCOM Lab

COMMIT;
END $$
DELIMITER ;

Execute the Comprehensive Stored Procedure

DATCOM Lab, Faculty of Data Science and Artificial Intelligence, NEU


CALL ProcessOrders(1001, 1, 150.00); -- Expected: Order processed successfully

CALL ProcessOrders(1001, 1, 150.00); -- Expected: Error, order already exists

CALL ProcessOrders(1002, 999, 200.00); -- Expected: Error, customer does not exist
10
DATCOM Lab, Faculty of Data Science and Artificial Intelligence, NEU

Submission
• SQL scripts for each stored procedure created in the lab.
• Output results from executing each stored procedure.
• A brief report explaining the challenges faced and how they were overcome.

Assessment Criteria
• Correctness and completeness of the stored procedures.
• Proper use of MySQL features such as variables, control structures, error handling, cursors, and
dynamic SQL.
• Clarity and organization of the SQL scripts and report.

Conclusion
This lab provides a comprehensive hands-on experience in working with MySQL Stored Procedures,
reinforcing the theoretical knowledge gained in the lecture. By completing these exercises, students will
be well-equipped to apply stored procedures in real-world database management tasks.

References
• MySQL Views Tutorial
• MySQL Stored Procedures Tutorial
• W3Schools SQL View

• W3Schools SQL Stored Procedures

@DATCOM Lab 11

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy