diff --git a/10_stored_routines_as_functions/script.sql b/10_stored_routines_as_functions/script.sql index e3ee0ca..336ed33 100644 --- a/10_stored_routines_as_functions/script.sql +++ b/10_stored_routines_as_functions/script.sql @@ -1 +1,22 @@ --- Write your SQL code here \ No newline at end of file +DELIMITER // + CREATE FUNCTION CalculateBatchProductionDuration(batch_id INT) + RETURNS INT DETERMINISTIC BEGIN DECLARE start_date DATE; +DECLARE end_date DATE; DECLARE duration INT; +SELECT StartDate, EndDate INTO start_date, end_date FROM ProductionBatch WHERE BatchID = batch_id; +SET duration = DATEDIFF(end_date, start_date); +RETURN duration; +END // +DELIMITER ; + +ALTER TABLE RawMaterial +ADD COLUMN PricePerUnit DECIMAL(10,2) NOT NULL DEFAULT 0; +DELIMITER // +CREATE FUNCTION GetTotalRawMaterialValue() +RETURNS DECIMAL(10,2) DETERMINISTIC BEGIN DECLARE total_value DECIMAL(10,2) DEFAULT 0; +SELECT SUM(QuantityOnHand * PricePerUnit) INTO total_value FROM RawMaterial; +RETURN total_value; +END // +DELIMITER ; + + +-- Write your SQL code here diff --git a/11_views/script.sql b/11_views/script.sql index e3ee0ca..0af9665 100644 --- a/11_views/script.sql +++ b/11_views/script.sql @@ -1 +1,19 @@ --- Write your SQL code here \ No newline at end of file +CREATE VIEW SupplierInventoryStatus + AS SELECT s.SupplierID, s.SupplierName, r.MaterialID, r.MaterialName, i.StockLevel, r.ReorderLevel, + CASE WHEN i.StockLevel <= r.ReorderLevel + THEN 'Reorder Needed' ELSE 'Sufficient Stock' + END AS ReorderStatus + FROM Supplier s INNER JOIN RawMaterial r ON s.SupplierID = r.SupplierID + INNER JOIN Inventory i ON r.MaterialID = i.MaterialID; + +CREATE TABLE Customers + ( CustomerID INT PRIMARY KEY, CustomerName VARCHAR(100), + ContactInfo VARCHAR(200) ); +CREATE VIEW FinancialOrderSummary + AS SELECT o.OrderID, + c.CustomerID, c.CustomerName, c.ContactInfo, o.OrderDate, + o.TotalAmount AS OrderValue, o.OrderStatus AS OrderStatus + FROM SalesOrder o INNER JOIN Customers c ON o.CustomerID = c.CustomerID; + + +-- Write your SQL code here diff --git a/12_database_transactions/script.sql b/12_database_transactions/script.sql index e3ee0ca..a753980 100644 --- a/12_database_transactions/script.sql +++ b/12_database_transactions/script.sql @@ -1 +1,19 @@ --- Write your SQL code here \ No newline at end of file +START TRANSACTION; +-- Step 1: Deduct inventory levels for materials in the sales order +UPDATE Inventory AS i +INNER JOIN SalesOrderDetails AS sod ON i.MaterialID = sod.MaterialID +SET i.StockLevel = i.StockLevel - sod.Quantity +WHERE sod.OrderID = 1; -- Replace 1 with the actual OrderID +-- Step 2: Check if any inventory level is negative +IF EXISTS (SELECT 1 FROM Inventory WHERE StockLevel < 0) THEN + ROLLBACK; + SIGNAL SQLSTATE '45000' + SET MESSAGE_TEXT = 'Transaction aborted: Insufficient inventory to process the order.'; +END IF; +-- Step 3: Update the sales order status to "Completed" +UPDATE SalesOrder +SET OrderStatus = 'Completed' +WHERE OrderID = 1; -- Replace 1 with the actual OrderID +-- Commit the transaction +COMMIT; +-- Write your SQL code here diff --git a/2_base_tables/script.sql b/2_base_tables/script.sql index e3ee0ca..df52856 100644 --- a/2_base_tables/script.sql +++ b/2_base_tables/script.sql @@ -1 +1,41 @@ --- Write your SQL code here \ No newline at end of file +CREATE TABLE QualityCheck + ( CheckID INT AUTO_INCREMENT PRIMARY KEY, BatchID INT NOT NULL, CheckDate DATE NOT NULL, + Result VARCHAR(50) NOT NULL, DefectDetails TEXT, + INDEX (BatchID), FOREIGN KEY (BatchID) REFERENCES ProductionBatch(BatchID) ) + ENGINE=InnoDB; +CREATE TABLE RawMaterial + ( MaterialID INT AUTO_INCREMENT PRIMARY KEY, MaterialName VARCHAR(100) NOT NULL, + QuantityOnHand INT NOT NULL, SupplierID INT NOT NULL, + ReorderLevel INT NOT NULL, INDEX (MaterialName), + INDEX (SupplierID),FOREIGN KEY (SupplierID) REFERENCES Supplier(SupplierID) ) + ENGINE=InnoDB; +CREATE TABLE Supplier + ( SupplierID INT AUTO_INCREMENT PRIMARY KEY, SupplierName VARCHAR(100) NOT NULL, + ContactInfo VARCHAR(255), DeliveryPerformance VARCHAR(50), PaymentTerms VARCHAR(100), + INDEX (SupplierName) ) + ENGINE=InnoDB; +CREATE TABLE Inventory + ( InventoryID INT AUTO_INCREMENT PRIMARY KEY, MaterialID INT NOT NULL, + StockLevel INT NOT NULL, LastUpdated DATETIME NOT NULL, + Location VARCHAR(100),INDEX (MaterialID),INDEX (Location), + FOREIGN KEY (MaterialID) REFERENCES RawMaterial(MaterialID) ) + ENGINE=InnoDB; +CREATE TABLE Employee + ( EmployeeID INT AUTO_INCREMENT PRIMARY KEY, Name VARCHAR(100) NOT NULL, + Role VARCHAR(50) NOT NULL, Department VARCHAR(50) NOT NULL, + INDEX (Name),INDEX (Department)) + ENGINE=InnoDB; +CREATE TABLE TrainingRecord + ( TrainingRecordID INT AUTO_INCREMENT PRIMARY KEY, + EmployeeID INT NOT NULL, TrainingDetails TEXT NOT NULL,INDEX (EmployeeID), + FOREIGN KEY (EmployeeID) REFERENCES Employee(EmployeeID) ) + ENGINE=InnoDB; + + + + + + + + +-- Write your SQL code here diff --git a/3_normal_triggers/script.sql b/3_normal_triggers/script.sql index e3ee0ca..357ceb8 100644 --- a/3_normal_triggers/script.sql +++ b/3_normal_triggers/script.sql @@ -1 +1,47 @@ --- Write your SQL code here \ No newline at end of file +CREATE TABLE `Inventory_History` ( + `HistoryID` int NOT NULL AUTO_INCREMENT, + `InventoryID` int NOT NULL, + `MaterialID` int NOT NULL, + `Previous_StockLevel` int NOT NULL, + `Previous_LastUpdated` datetime NOT NULL, + `Previous_Location` varchar(100) DEFAULT NULL, + `New_StockLevel` int NOT NULL, + `New_LastUpdated` datetime NOT NULL, + `New_Location` varchar(100) DEFAULT NULL, + `ChangeTimestamp` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`HistoryID`) +) ENGINE=InnoDB +CREATE TRIGGER TRG_AFTER_UPDATE_ON_Inventory +AFTER UPDATE ON Inventory +FOR EACH ROW +INSERT INTO Inventory_History ( + InventoryID, + MaterialID, + StockLevel, + LastUpdated, + Location, + Previous_StockLevel, + Previous_LastUpdated, + Previous_Location +) +VALUES ( + OLD.InventoryID, + OLD.MaterialID, + OLD.StockLevel, + OLD.LastUpdated, + OLD.Location, + NEW.StockLevel, + NEW.LastUpdated, + NEW.Location +); +DELIMITER // +CREATE TRIGGER TRG_BEFORE_INSERT_ProductionBatch +BEFORE INSERT ON ProductionBatch +FOR EACH ROW +BEGIN + IF NEW.EndDate < NEW.StartDate THEN + SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'End Date must be greater than or equal to Start Date'; + END IF; +END// +DELIMITER ; +-- Write your SQL code here diff --git a/4_check_constraints/script.sql b/4_check_constraints/script.sql index e3ee0ca..2bb2290 100644 --- a/4_check_constraints/script.sql +++ b/4_check_constraints/script.sql @@ -1 +1,17 @@ --- Write your SQL code here \ No newline at end of file +CREATE TABLE `ProductionBatch` ( + `BatchID` int NOT NULL AUTO_INCREMENT, + `StartDate` date NOT NULL, + `EndDate` date NOT NULL, + `Volume` decimal(10,2) NOT NULL, + `Status` varchar(50) NOT NULL, + PRIMARY KEY (`BatchID`), + CONSTRAINT `productionbatch_chk_1` CHECK ((`EndDate` >= `StartDate`)) +INDEX (StartDate), INDEX (Status)) ENGINE=InnoDB +CREATE TABLE SalesOrder + ( OrderID INT AUTO_INCREMENT PRIMARY KEY, CustomerID INT NOT NULL, OrderDate DATE NOT NULL, + TotalAmount DECIMAL(10,2) NOT NULL,CHECK (TotalAmount > 0), + OrderStatus VARCHAR(20) NOT NULL, INDEX (CustomerID) + ) ENGINE=InnoDB; + + +-- Write your SQL code here diff --git a/5_temporal_triggers/script.sql b/5_temporal_triggers/script.sql index e3ee0ca..d3745c4 100644 --- a/5_temporal_triggers/script.sql +++ b/5_temporal_triggers/script.sql @@ -1 +1,29 @@ --- Write your SQL code here \ No newline at end of file +CREATE TABLE employee_archive + ( ArchiveID INT AUTO_INCREMENT PRIMARY KEY, EmployeeID INT NOT NULL, Name VARCHAR(100), + Role VARCHAR(50), Department VARCHAR(50), + ArchiveDate DATETIME NOT NULL ) ENGINE=InnoDB; +CREATE TRIGGER TRG_BEFORE_DELETE_ON_employees + BEFORE DELETE ON Employee FOR EACH ROW INSERT INTO + employee_archive SET EmployeeID = OLD.EmployeeID, Name = OLD.Name, + Role = OLD.Role, Department = OLD.Department, + ArchiveDate = CURRENT_TIMESTAMP; +CREATE TABLE `OrderHistory` ( `HistoryID` int NOT NULL AUTO_INCREMENT, + `OrderID` int NOT NULL, + `PackagingCompletionTime` datetime NOT NULL, + PRIMARY KEY (`HistoryID`), + FOREIGN KEY (`OrderID`) + REFERENCES `SalesOrder`(`OrderID`) ) ENGINE=InnoDB; +DELIMITER // + CREATE TRIGGER TRG_AFTER_UPDATE_SalesOrder + AFTER UPDATE ON SalesOrder + FOR EACH ROW BEGIN + IF NEW.OrderStatus = 'Packaged' AND OLD.OrderStatus != 'Packaged' + THEN INSERT INTO OrderHistory (OrderID, PackagingCompletionTime) + VALUES (NEW.OrderID, NOW()); +END IF; +END // +DELIMITER ; + + + +-- Write your SQL code here diff --git a/9_stored_routines_as_procedures/script.sql b/9_stored_routines_as_procedures/script.sql index e3ee0ca..6a4f229 100644 --- a/9_stored_routines_as_procedures/script.sql +++ b/9_stored_routines_as_procedures/script.sql @@ -1 +1,51 @@ --- Write your SQL code here \ No newline at end of file +DELIMITER $$ + +CREATE PROCEDURE `GetSalesOrderSummary`(IN StartDate DATE, IN EndDate DATE, OUT TotalAmount DOUBLE) +BEGIN + DECLARE totalSales DOUBLE DEFAULT 0.00; + DECLARE currentStatus VARCHAR(50); + DECLARE done INT DEFAULT 0; + + -- Declare a cursor to iterate through statuses and calculate total sales + DECLARE salesCursor CURSOR FOR + SELECT + Status, SUM(Amount) AS TotalAmount + FROM + SalesOrder + WHERE + OrderDate BETWEEN StartDate AND EndDate + GROUP BY + Status; + + -- Declare a handler for the cursor completion + DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1; + + -- Initialize total sales + SET TotalAmount = 0.00; + + -- Open the cursor + OPEN salesCursor; + + read_loop: LOOP + FETCH salesCursor INTO currentStatus, totalSales; + IF done THEN + LEAVE read_loop; + END IF; + -- Add each status's total sales to the output + SET TotalAmount = TotalAmount + totalSales; + END LOOP; + + -- Close the cursor + CLOSE salesCursor; +END $$ + +DELIMITER ; + +DELIMITER $$ + CREATE PROCEDURE `GetProductionReport`( IN StartDate DATE, IN EndDate DATE ) + BEGIN SELECT BatchID, StartDate, EndDate, Volume, + Status FROM ProductionBatch WHERE StartDate + BETWEEN StartDate AND EndDate OR EndDate BETWEEN StartDate AND EndDate; +END $$ +DELIMITER ; + diff --git a/README.md b/README.md index 8728c63..74c141e 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,4 @@ +[![Review Assignment Due Date](https://classroom.github.com/assets/deadline-readme-button-22041afd0340ce965d47ae6ef1cefeee28c7c493a6346c4f15d667ab976d596c.svg)](https://classroom.github.com/a/fbNyN1as) # BBT3104: Advanced Database Sytems Semester Project | **Key** | Value |