变量
- 局部变量:declare:|用户可以使用DECLARE关键字来定义变量。然后可以为变量赋值。这些变量的作用范围是BEGIN…END程序段中
- 用户变量:@变量名:eg:@a 定义用户变量,作用域在整个链接
- 会话变量:在每次连接成功后会将全局变量拷贝一份到当前回话:set session var_name = value; show variables like “autocommit”;
- 全局变量: set global var_name = value;
https://www.cnblogs.com/gavin110-lgy/p/5772577.html
存储过程
delimiter $$
drop procedure if exists create_data_for_test2;
create procedure create_data_for_test2(in num int,out total int)
begin
declare count int default 0;
declare batch_num int default 0;
dd:loop
START TRANSACTION;--手动提交事务,提高效率
batch:loop
insert into test2(b,c,d,e) values(round(rand()*10),round(rand()*10),round(rand()*10),round(rand()*count));
set count=count+1;
set batch_num:=batch_num+1;
if count>=num then
leave dd;
end if;
if batch_num>=10 then
commit;
set batch_num=0;
leave batch;
end if;
end loop batch;
end loop dd;
commit;
select count(*) into total from test2;
end;$$
delimiter ;
show procedure status;
drop procedure create_data;
函数
delimiter $$
create function get_b_by_a(a1 int)
returns int
begin
declare b_test2 int default 0;
select b into b_test2 from test2 where a=a1;
return b_test2;
end$$
delimiter ;
show function status\G;
函数和存储过程的区别
- 返回值上的不同:函数将向调用者返回一个且仅返回一个结果值;存储过程将返回一个或多个结果集,或者无返回值
- 调用方式上的不同:函数嵌入在sql中使用的,可以在select中调用;存储过程只能通过call语句进行调用
- 参数的不同:存储函数的参数类型类似于IN参数;存储过程的参数类型有三种、IN参数、OUT参数、INOUT参数