DELIMITER $$
CREATE FUNCTION CustomerLevel(p_creditLimit double) RETURNS VARCHAR(10)
DETERMINISTIC
BEGIN
DECLARE lvl varchar(10);
IF p_creditLimit > 50000 THEN
SET lvl = 'PLATINUM';
ELSEIF (p_creditLimit <= 50000 AND p_creditLimit >= 10000) THEN
SET lvl = 'GOLD';
ELSEIF p_creditLimit < 10000 THEN
SET lvl = 'SILVER';
END IF;
RETURN (lvl);
END $$
DELIMITER ;
SELECT
customerName, CustomerLevel(creditLimit)
FROM
customers
ORDER BY customerName;
执行上面查询语句,得到以下结果 -
+------------------------------------+----------------------------+
| customerName | CustomerLevel(creditLimit) |
+------------------------------------+----------------------------+
| Alpha Cognac | PLATINUM |
| American Souvenirs Inc | SILVER |
| Amica Models & Co. | PLATINUM |
| ANG Resellers | SILVER |
| Anna's Decorations, Ltd | PLATINUM |
| Anton Designs, Ltd. | SILVER |
| Asian Shopping Network, Co | SILVER |
| Asian Treasures, Inc. | SILVER |
| Atelier graphique | GOLD |
| Australian Collectables, Ltd | PLATINUM |
| Australian Collectors, Co. | PLATINUM |
|************** 此处省略了一大波数据 *********************************|
| Vitachrome Inc. | PLATINUM |
| Volvo Model Replicas, Co | PLATINUM |
| Warburg Exchange | SILVER |
| West Coast Collectables Co. | PLATINUM |
+------------------------------------+----------------------------+
122 rows in set
DELIMITER $$
CREATE PROCEDURE GetCustomerLevel(
IN p_customerNumber INT(11),
OUT p_customerLevel varchar(10)
)
BEGIN
DECLARE creditlim DOUBLE;
SELECT creditlimit INTO creditlim
FROM customers
WHERE customerNumber = p_customerNumber;
SELECT CUSTOMERLEVEL(creditlim)
INTO p_customerLevel;
END $$
DELIMITER ;