存储过程有什么优缺点?为什么要用存储过程?或者在什么情况下才用存储过程?
最直白的好处是存储过程比较快。
1、利用存储过程,给Employee表添加一条业务部门员工的信息。
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' );
2、利用存储过程输出所有客户姓名、客户订购金额及其相应业务员的姓名。
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();
3、利用存储过程查找某员工的员工编号、订单编号、销售金额。
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('张小梅');
4、相关
5、插入一条学生记录,判断学号是否存在。
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');