自学内容网 自学内容网

数据库作业6

视图作业
1. 创建视图v_emp_dept_id_1

 

CREATE VIEW v_emp_dept_id_1 AS
SELECT emp_name, address
FROM emp
WHERE dept_id = (SELECT dept_id FROM dept WHERE dept_name = '销售部');


2. 创建视图v_emp_dept
 

CREATE VIEW v_emp_dept AS
SELECT e.emp_name, e.address, d.dept_name
FROM emp e
JOIN dept d ON e.dept_id = d.dept_id
WHERE d.dept_name = '销售部';


3. 创建视图v_dept_emp_count
 

CREATE VIEW v_dept_emp_count AS
SELECT d.dept_name, COUNT(e.emp_id) AS emp_count, AVG(e.salary) AS avg_salary
FROM dept d
LEFT JOIN emp e ON d.dept_id = e.dept_id
GROUP BY d.dept_id;


4. 修改视图v_emp_dept
 

ALTER VIEW v_emp_dept AS
SELECT e.emp_name, e.address, e.salary, d.dept_name
FROM emp e
JOIN dept d ON e.dept_id = d.dept_id
WHERE d.dept_name = '销售部';


5. 查看视图
查看视图名称:

SHOW FULL TABLES WHERE TABLE_TYPE LIKE 'VIEW';


查看视图结构:

DESCRIBE v_emp_dept_id_1;
DESCRIBE v_emp_dept;
DESCRIBE v_dept_emp_count;


查看创建视图语句:

SHOW CREATE VIEW v_emp_dept_id_1;
SHOW CREATE VIEW v_emp_dept;
SHOW CREATE VIEW v_dept_emp_count;


6. 删除视图
 

DROP VIEW IF EXISTS v_emp_dept_id_1, v_emp_dept, v_dept_emp_count;


存储过程作业
1. 创建存储过程s1

 

DELIMITER //
CREATE PROCEDURE s1()
BEGIN
  SELECT SUM(salary) AS total_salary FROM emp;
END //
DELIMITER ;


2. 调用存储过程s1
 

CALL s1();


3. 创建存储过程s2
 

DELIMITER //
CREATE PROCEDURE s2(IN emp_name CHAR(20), OUT address VARCHAR(200))
BEGIN
  SELECT address INTO address FROM emp WHERE emp_name = emp_name;
END //
DELIMITER ;


4. 调用存储过程s2
 

CALL s2('张晓红', @address);
SELECT @address;


5. 创建存储过程avg_sai
 

DELIMITER //
CREATE PROCEDURE avg_sai(IN dept_id INT, IN gender CHAR(2), OUT avg_salary DECIMAL(10,2))
BEGIN
  SELECT AVG(salary) INTO avg_salary FROM emp WHERE dept_id = dept_id AND gender = gender;
END //
DELIMITER ;


6. 调用存储过程avg_sai
 

CALL avg_sai(1, '男', @avg_salary);
SELECT @avg_salary;


7. 删除存储过程
 

DROP PROCEDURE IF EXISTS s1, s2, avg_sai;


 


原文地址:https://blog.csdn.net/m0_73875436/article/details/140441460

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!