存儲過程有什麼優缺點?爲何要用存儲過程?或者在什麼狀況下才用存儲過程?html
最直白的好處是存儲過程比較快。測試
一、利用存儲過程,給Employee表添加一條業務部門員工的信息。spa
DROP PROCEDURE IF EXISTS insert_business_employee; DELIMITER // CREATE PROCEDURE insert_business_employee( IN employee_no_in varchar(8), IN employee_name_in varchar(10), IN sex_in char(1), IN birthday_in date, IN address_in varchar(50), IN telephone_in varchar(20), IN hiredate_in date, -- IN department_in varchar(30), IN headship_in varchar(10), IN salary_in decimal(8,2) ) BEGIN INSERT INTO employee (employee_no, employee_name, sex, birthday, address, telephone, hiredate, department, headship, salary) VALUES (employee_no_in, employee_name_in, sex_in, birthday_in, address_in, telephone_in, hiredate_in, '業務部', headship_in, salary_in); END // DELIMITER ; CALL insert_business_employee( '2222', '無極', 'F', '2001-10-22', '北海道', '1231232', '2001-10-22', '老闆', '1333232' );
二、利用存儲過程輸出全部客戶姓名、客戶訂購金額及其相應業務員的姓名。日誌
DROP PROCEDURE IF EXISTS print_transaction; DELIMITER // CREATE PROCEDURE print_transaction() BEGIN SELECT customer_name, order_sum, employee_name FROM customer x LEFT JOIN order_master y ON x.customer_no = y.customer_no LEFT JOIN employee z ON y.saler_no = z.employee_no; END // DELIMITER ; CALL print_transaction();
三、利用存儲過程查找某員工的員工編號、訂單編號、銷售金額。code
DROP PROCEDURE IF EXISTS select_employee_performance; DELIMITER // CREATE PROCEDURE select_employee_performance( IN employee_name_in varchar(10) ) BEGIN SELECT saler_no, order_no, order_sum FROM employee LEFT JOIN order_master ON employee_no = saler_no WHERE employee_name = employee_name_in ORDER BY saler_no; END // DELIMITER ; CALL select_employee_performance('張小梅');
四、相關orm
WEB 開發相關筆記 #05# BUG 日誌 持續更新htm
五、插入一條學生記錄,判斷學號是否存在。blog
DROP PROCEDURE IF EXISTS inserStu; DELIMITER // CREATE PROCEDURE inserStu( IN id_in INT, IN name_in VARCHAR(50) ) BEGIN IF EXISTS (SELECT * FROM stu WHERE id = id_in) THEN SELECT "學號已存在"; ELSE INSERT INTO stu (id, name) VALUES (id_in, name_in); SELECT "插入成功"; END IF; END // DELIMITER ; -- 測試 -- CALL inserStu(1, 'wang'); -- CALL inserStu(1, 'wang'); -- CALL inserStu(333, 'wang');