Day 11
1)
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetCustomerlevel`(in customernumber int)
BEGIN
DECLARE customerCreditLimit INT;
DECLARE customerLevel VARCHAR(255);
SELECT creditlimit INTO customerCreditLimit
FROM Customers
WHERE customernumber = customerNumber
LIMIT 1;
SELECT customerCreditLimit AS DebugCreditLimit;
IF customerCreditLimit IS NULL THEN
SET customerLevel = 'Unknown'; -- Handle NULL values
ELSEIF customerCreditLimit > 100000 THEN
SET customerLevel = 'Platinum';
ELSEIF customerCreditLimit BETWEEN 25000 AND 100000 THEN
SET customerLevel = 'Gold';
ELSE
SET customerLevel = 'Silver';
END IF;
SELECT customerLevel AS DebugCustomerLevel;
SELECT customerLevel AS CustomerLevel;
END
2)
CREATE DEFINER=`root`@`localhost` PROCEDURE `Get_country_payments`( inputYear INT, IN
inputCountry VARCHAR(255))
BEGIN
SELECT
YEAR(paymentDate) AS PaymentYear,
country,
CONCAT(FORMAT(SUM(amount) / 1000, 0), 'K') AS TotalAmount
FROM Payments
JOIN Customers ON Payments.customerNumber = Customers.customerNumber
WHERE YEAR(paymentDate) = inputYear AND country = inputCountry
GROUP BY PaymentYear, country;
END
Day 12
2)
CREATE DEFINER=`root`@`localhost` FUNCTION `calc_age`(dateOfBirth DATE) RETURNS varchar(255)
CHARSET latin1
DETERMINISTIC
begin
DECLARE years INT;
DECLARE months INT;
DECLARE ageString VARCHAR(255);
SELECT
TIMESTAMPDIFF(YEAR, dateOfBirth, CURDATE()) AS years,
TIMESTAMPDIFF(MONTH, dateOfBirth, CURDATE()) % 12 AS months
INTO years, months;
SET ageString = CONCAT(years, ' years ', months, ' months');
RETURN ageString;
END
Day 14
1)
CREATE DEFINER=`root`@`localhost` PROCEDURE `InsertEmpEH`(
IN p_EmpID INT,
IN p_EmpName VARCHAR(255),
IN p_EmailAddress VARCHAR(255)
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
-- Custom error message for SQL exception
SELECT 'Error occurred' AS ErrorMessage;
END;
-- Start the transaction
START TRANSACTION;
-- Attempt to insert into Emp_EH
INSERT INTO Emp_EH (EmpID, EmpName, EmailAddress)
VALUES (p_EmpID, p_EmpName, p_EmailAddress);
-- Commit the transaction if no errors
COMMIT;
-- Custom success message
SELECT 'Data inserted successfully' AS Message;
END
Day 15
CREATE DEFINER=`root`@`localhost` TRIGGER `emp_bit_BEFORE_INSERT` BEFORE INSERT ON
`emp_bit` FOR EACH ROW BEGIN
IF NEW.Working_hours < 0 THEN
SET NEW.Working_hours = ABS(NEW.Working_hours);
END IF;
END