DBMS__Lab_4_1___STORED_PROC
DBMS__Lab_4_1___STORED_PROC
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
Required Tools
• MySQL Workbench or any SQL editor that connects to your MySQL database.
• A text editor for writing and saving SQL scripts.
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)
);
(’Tablet’, 300.00),
(’Headphones’, 100.00);
END $$
DELIMITER ;
DELIMITER ;
END $$
DELIMITER ;
DECLARE vip_cursor CURSOR FOR SELECT id, name FROM customers WHERE type = ’VIP’;
7
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 ;
Managing Privileges
GRANT EXECUTE ON PROCEDURE lab_stored_procedures.GetAllCustomers TO ’student_user’@’localhost’;
8
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;
COMMIT;
END $$
DELIMITER ;
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
@DATCOM Lab 11