MySQL-stored function practice

Create table and insert data

​	字段名	 数据类型       主键    外键   非空    唯一   自增
​	id         INT	        是 	    否 	  是      是 	 否
​	name	VARCHAR(50)     否      否 	  是      否  	 否
​	glass   VARCHAR(50)     否      否 	  是      否  	 否
mysql> create table sch(
    -> id int primary key,
    -> name varchar(50) not null,
    -> glass varchar(50) not null);
​	sch表内容
​	id	  name	     glass
​	1	 xiaommg     glass 12 	 xiaojun      glass 2
mysql> insert into sch values (1,'xiaommg','glass 1'),(2,'xiaojun','glass 2');

insert image description here

​1. Create a storage function that can count the number of records in the table. The function name is count_sch()

mysql> \d $
mysql> create function count_sch()
    -> returns int 
    -> begin
    -> declare n int default 0;
    -> select count(*) into n from sch;
    -> return n;
    -> end$

insert image description here

2. Create a stored procedure avg_sai, which has 3 parameters, namely deptno, job, which receives the average salary, the function query emp table dept is 30, and job is the average salary of the salesperson.
insert image description here

mysql> create procedure avg_sai(in a int,in b varchar(255),out avg_salary int)
    -> begin
    -> select avg(sai) into avg_salary
    -> from emp
    -> where deptno=a and job=b;
    -> end$$
mysql> set @avg_salary=0$$
mysql> CALL avg_sai(30, '销售员', @avg_salary)$$
mysql> select @avg_salary$$
+-------------+
| @avg_salary |
+-------------+
|    14000.00 |
+-------------+

Guess you like

Origin blog.csdn.net/HealerCCX/article/details/131668424