创建视图v_emp_dept_id_1,查询销售部门的员工姓名和家庭住址
CREATE VIEW v_emp_dept_id_1 AS
SELECT e.emp_name,e.address FROM dept d, emp e WHERE e.dept_id =
(SELECT dept_id FROM dept WHERE dept_name = '销售部');
SELECT * FROM v_emp_dept_id_1;
创建视图v_emp_dept,查询销售部门员工姓名和家庭住址及部门名称。
CREATE VIEW v_emp_dept AS
SELECT e.emp_name,e.address,d.dept_name FROM dept d, emp e WHERE e.dept_id =
(SELECT dept_id FROM dept WHERE dept_name = '销售部');
SELECT * FROM v_emp_dept;
创建视图v_dept_emp_count(dept_name,emp_count,avg_salay),统计每个部门人数并计算平均工资。
CREATE VIEW v_dept_emp_count(dept_name,emp_count,avg_salay) AS
SELECT d.dept_name,a.emp_count,a.avg_salay FROM dept d,
(SELECT dept_id,COUNT(1) AS emp_count,AVG(salary) AS avg_salay FROM emp GROUP BY dept_id) a
WHERE d.dept_id = a.dept_id;
SELECT * FROM v_dept_emp_count;
修改视图v_emp_dept,查询销售部门员工姓名、家庭住址、工资和部门名称。
ALTER VIEW v_emp_dept AS
SELECT e.emp_name,e.address,e.salary,d.dept_name FROM dept d, emp e
WHERE e.dept_id =
(SELECT dept_id FROM dept WHERE dept_name = '销售部');
SELECT * FROM v_emp_dept;
查看视图名称;
查看视图结构;
DESC v_emp_dept;
查看创建视图语句;
SHOW TABLE STATUS LIKE 'v_emp_dept';
删除以上三个视图。
DROP VIEW v_emp_dept;
DROP VIEW v_emp_dept_id_1;
DROP VIEW v_dept_emp_count;
SELECT * FROM emp;
SELECT * FROM dept;
创建一个提取emp表所有员工工资和的存储过程s1
DELIMITER $$
CREATE
/*[DEFINER = { user | CURRENT_USER }]*/
PROCEDURE `db_view`.`s1`()
/*LANGUAGE SQL
| [NOT] DETERMINISTIC
| { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA }
| SQL SECURITY { DEFINER | INVOKER }
| COMMENT 'string'*/
BEGIN
SELECT SUM(salary) FROM emp;
END$$
DELIMITER ;
调用存储过程s1
CALL s1();
创建存储过程s2,实现输入员工姓名后返回员工的家庭住址。
DELIMITER $$
CREATE
/*[DEFINER = { user | CURRENT_USER }]*/
PROCEDURE `db_view`.`s2`(IN in_name VARCHAR(20))
/*LANGUAGE SQL
| [NOT] DETERMINISTIC
| { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA }
| SQL SECURITY { DEFINER | INVOKER }
| COMMENT 'string'*/
BEGIN
SELECT address FROM emp WHERE emp_name = in_name;
END$$
DELIMITER ;
调用存储过程s2
CALL s2('张晓红');
创建一个存储过程avg_sai,有3个参数,分别是dept,gender,接收平均工资,功能查询emp表dept_id为1,gender为男的平均工资
DELIMITER $$
CREATE
/*[DEFINER = { user | CURRENT_USER }]*/
PROCEDURE `db_view`.`avg_sai`(IN in_dept_id INT,in_gender VARCHAR(2))
/*LANGUAGE SQL
| [NOT] DETERMINISTIC
| { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA }
| SQL SECURITY { DEFINER | INVOKER }
| COMMENT 'string'*/
BEGIN
SELECT AVG(salary)FROM
(SELECT * FROM emp WHERE dept_id = in_dept_id) a
WHERE gender = in_gender;
END$$
DELIMITER ;
调用存储过程avg_sai
CALL avg_sai(1,'男');
删除以上存储过程
DROP PROCEDURE s1;
DROP PROCEDURE s2;
DROP PROCEDURE avg_sai;