MYSQL stored procedures and stored functions and triggers

1, stored procedures and stored functions Overview

Stored procedures and functions for a set of SQL statements are compiled in advance and stored in the database, call stored procedures and functions can simplify a lot of work application developers to reduce the transmission of data between the database and application server, for improving data processing the efficiency is good.
The difference between the stored procedures and functions is that the function has to return, while the process is not stored.
Function: the process is a return value;
process: a function value is not returned;

2, stored procedures

2,1 create a stored procedure

语法:
	CREATE PROCEDURE procedure_name ([proc_parameter[,...]])
	begin
	-- SQL语句
	end ;
示例 :
	delimiter $
	create procedure pro_test1()
	begin
	select 'Hello Mysql' ;
	end$
	delimiter ;
delimiter说明: 
该关键字用来声明SQL语句的分隔符, 告诉MySQL解释器,该段命令是否已经结束了,mysql是否可以执行了。
默认情况下,delimiter是分号;。在命令行客户端中,如果有一行命令以分号结束,那么回车后,mysql将会执行该
命令。

2,1,1 variable definition
can be defined by a local variable DECLARE, the variable scope only BEGIN ... END block.

示例
	delimiter $
	create procedure pro_test2()
	begin
	declare num int default 5;
	select num+ 10;
	end$

Assignment 2,1,2set
direct assignment using the SET, or excipients can be assigned a constant expression, specific syntax is as follows:
the SET var_name = expr [, var_name = expr] ...

示例
	DELIMITER $
	CREATE PROCEDURE pro_test3()
	BEGIN
	DECLARE NAME VARCHAR(20);
	SET NAME = 'MYSQL';
	SELECT NAME ;
	END$

You can also select ... into an assignment by way of:

	DELIMITER $
	CREATE PROCEDURE pro_test5()
	BEGIN
	declare countnum int;
	select count(*) into countnum from city;
	select countnum;
	END$

2,1,3, if the condition is determined

示例
	delimiter $
	create procedure pro_test6()
	begin
	declare height  int default  175;
	declare description  varchar(50);
	if height >= 180 then
		set description = '身材高挑';
	elseif height >= 170 and height < 180 then
		set description = '标准身材';
	else
   	    set description = '一般身材';
	end if;
	 select description ;
	end$

As a result of the call:
Here Insert Picture Description
2,1,4 passing parameters
syntax

create procedure procedure_name([in/out/inout] 参数名  参数类型)
...
IN :  该参数可以作为输入,也就是需要调用方传入值 , 默认
OUT:  该参数作为输出,也就是该参数可以作为返回值
INOUT: 既可以作为输入参数,也可以作为输出参数

示例
	delimiter $
	create procedure pro_test5(in height int , out description varchar(100))
	begin
	if height >= 180 then
	  set description='身材高挑';
	elseif height >= 170 and height < 180 then
	  set description='标准身材';
	else
	  set description='一般身材';
	end if;
	end$
调用:
	call pro_test5(168, @description)$
	select @description$
小知识
	@description : 这种变量要在变量名称前面加上“@”符号,叫做用户会话变量,代表整个会话过程他都是有作用
的,这个类似于全局变量一样。
	@@global.sort_buffer_size : 这种在变量前加上 "@@" 符号, 叫做系统变量

Here Insert Picture Description
2,1,5case structure
grammatical structure

方式一 :
	CASE case_value
	WHEN when_value THEN statement_list
	[WHEN when_value THEN statement_list] ...
	[ELSE statement_list]
	END CASE;
方式二 :
	CASE
	WHEN search_condition THEN statement_list
	[WHEN search_condition THEN statement_list] ...
	[ELSE statement_list]
	END CASE;

Examples

	delimiter $
	create procedure pro_test9(month int)
	begin
	declare result varchar(20);
	case when month >= 1 and month <=3 then
	   set result = '第一季度';
	 when month >= 4 and month <=6 then
	   set result = '第二季度';
	 when month >= 7 and month <=9 then
	   set result = '第三季度';
	 when month >= 10 and month <=12 then
	   set result = '第四季度';
	end case;
	select concat('您输入的月份为 :', month , ' , 该月份为 : ' , result) as content ;
	end$

2,1,6while cycle
example

	delimiter $
	create procedure pro_test8(n int)
	begin
	declare total int default 0;
	declare num int default 1;
	while num<=n do
	  set total = total + num;
	  set num = num + 1;
	end while;
	 select total;
	end$

2,1,7 repeat structure
conditional loop control statements, when the condition of the loop is exited. while satisfying the conditions before execution, repeat that conditional loop exits.
Example: When until n = 0 when the loop exits.

	delimiter $
	create procedure pro_test10(n int)
	begin
	declare total int default 0;
	repeat
	  set total = total + n;
	  set n = n - 1;
	 until n=0 
	end repeat;
	 select total ;
	end$

2,1,8 loop statement
LOOP simple loop, loop exit conditions need to use other statements defined, you can usually use the LEAVE statement to achieve the specific syntax is as follows

如果不在 statement_list 中增加退出循环的语句,那么 LOOP 语句可以用来实现简单的死循环。
	[begin_label:] LOOP
	statement_list
	END LOOP [end_label]
leave语句
用来从标注的流程构造中退出,通常和 BEGIN ... END 或者循环一起使用。下面是一个使用 LOOP 和 LEAVE 的简
单例子 , 退出循环:
	delimiter $
	CREATE PROCEDURE pro_test11(n int)
	BEGIN
	declare total int default 0;
	ins: LOOP
	 IF n <= 0 then leave ins;//退出语句
	 END IF;
	  set total = total + n;
	  set n = n - 1;
	END LOOP ins;
	 select total;
	END$

2,1,9 cursor / cursor
cursor data type is used to store the query result set, the cursor can be used to process the result set during storage and circulation functions.

示例
从游标中一条一条获取查询出来的数据,如果取得次数多余查询出来数据得行数,会报错。
	create procedure pro_test11()
	begin
	declare e_id int(11);
	declare e_name varchar(50);
	declare e_age int(11);
	declare e_salary int(11);
	declare emp_result cursor for select * from emp;//定义游标
	open emp_result;//打开游标
	//取出游标中数据
	fetch emp_result into e_id,e_name,e_age,e_salary;
	 select concat('id=',e_id , ', name=',e_name, ', age=', e_age, ', 薪资为:
	',e_salary);
	fetch emp_result into e_id,e_name,e_age,e_salary;
	 select concat('id=',e_id , ', name=',e_name, ', age=', e_age, ', 薪资为:
	',e_salary);
	close emp_result;//关闭游标
	end$

By cyclic structure, acquiring data cursor:

DELIMITER $
create procedure pro_test12()
begin
DECLARE id int(11);
DECLARE name varchar(50);
DECLARE age int(11);
DECLARE salary int(11);
DECLARE has_data int default 1;
DECLARE emp_result CURSOR FOR select * from emp;//定义游标
//声明了handler,当从游标中取不到数据得时候退出。
//注意,声明得位置要在游标下面,has_data在上面定义。
DECLARE EXIT HANDLER FOR NOT FOUND set has_data = 0;
open emp_result;//打开游标
repeat
 fetch emp_result into id , name , age , salary;
  select concat('id为',id, ', name 为' ,name , ', age为 ' ,age , ', 薪水为: ',
salary);
 until has_data = 0//退出条件
end repeat;
close emp_result;
end$

2,2 call a stored procedure

call procedure_name() ;

2,3 View Stored Procedures

-- 查询db_name数据库中的所有的存储过程
select name from mysql.proc where db='db_name';
-- 查询存储过程的状态信息
show procedure status;
-- 查询某个存储过程的定义
show create procedure test.pro_test1 \G;

2,4 delete stored procedure

DROP PROCEDURE [IF EXISTS] sp_name ;

3, memory function

Create a sample 3,1

delimiter $
create function count_city(countryId int)
returns int//返回值类型定义
begin
declare cnum int ;
select count(*) into cnum from city where country_id = countryId;
return cnum;
end$

3,2 call a stored function

不能用call调用了
select count_city(1);
select count_city(2);

3,3 delete stored functions

drop function fun1$

4, flip-flop

Description: A trigger is associated with a table of database objects, refer to before insert / update / delete or after the trigger and the trigger execute SQL statements defined in the collection. This feature can facilitate the application of the trigger end of the database to ensure data integrity, logging, data verification operation.
Use aliases OLD and NEW references to record changes in the content of the flip-flop, which is similar to the other database. Now triggers also only supports row-level trigger, does not support the statement-level trigger.
Here Insert Picture Description
4,1 grammatical structure

create trigger trigger_name
before/after insert/update/delete
on tbl_name
[ for each row ]  -- 行级触发器
begin
trigger_stmt ;
end;

Examples

创建 insert 型触发器,完成插入数据时的日志记录 :
	After insert 在插入后执行的触发器
	For each row 行级触发器
	On emp 作用于emp表

DELIMITER $
create trigger emp_logs_insert_trigger
after insert
on emp
for each row
begin
 insert into emp_logs (id,operation,operate_time,operate_id,operate_params)
values(null,'insert',now(),new.id,concat('插入后(id:',new.id,', name:',new.name,',
age:',new.age,', salary:',new.salary,')'));
end $
创建 update 型触发器,完成更新数据时的日志记录 :
DELIMITER $
create trigger emp_logs_update_trigger
after update
on emp
for each row
begin
 insert into emp_logs (id,operation,operate_time,operate_id,operate_params)
values(null,'update',now(),new.id,concat('修改前(id:',old.id,', name:',old.name,',
age:',old.age,', salary:',old.salary,') , 修改后(id',new.id, 'name:',new.name,',
age:',new.age,', salary:',new.salary,')'));                             
end $
创建delete 行的触发器 , 完成删除数据时的日志记录 :
DELIMITER $
create trigger emp_logs_delete_trigger
after delete
on emp
for each row
begin
 insert into emp_logs (id,operation,operate_time,operate_id,operate_params)
values(null,'delete',now(),old.id,concat('删除前(id:',old.id,', name:',old.name,',
age:',old.age,', salary:',old.salary,')'));                                  
end $

test

insert into emp(id,name,age,salary) values(null, '光明左使',30,3500);
insert into emp(id,name,age,salary) values(null, '光明右使',33,3200);
update emp set age = 39 where id = 3;
delete from emp where id = 5;

4,2 delete trigger
// If no schema_name, defaults to the current database.
drop trigger [schema_name.] trigger_name

4,3 View trigger
information triggers can be viewed by executing SHOW TRIGGERS command state and grammar.
show triggers;

Published 81 original articles · won praise 5 · views 20000 +

Guess you like

Origin blog.csdn.net/qq_36205206/article/details/103496066