一、函数,参考博客:https://www.cnblogs.com/progor/p/8871480.html
/* 函数:函数只会返回一个值,不允许返回一个结果集。函数强调返回值,所以不允许返回多个值的情况,即使是查询语句。多个入参之间使用逗号分隔。 注意事项:在函数中,如果查询的表中字段与参数名相同,需要给字段名前面加上别名,不然在识别的时候有问题,程序不会报错,但查询结果有问题。 */ drop function if exists myf; create function myf(region_code varchar(10)) returns int begin declare c int; -- 定义变量,需要将查询结果赋值给变量select xxx into c; select pm10 from data_region_month t where t.region_code = region_code limit 1 into c; return c; end; select myf('411025'); select myf(region_code) from data_region_month;
二、存储过程,参考博客:https://www.cnblogs.com/chushiyaoyue/p/5945974.html
/* 存储过程:共有三种参数类型,IN,OUT,INOUT IN 输入参数: 表示该参数的值必须在调用存储过程时指定,在存储过程中修改该参数的值不能被返回,为默认值。 OUT 输出参数: 该值可在存储过程内部被改变,并可返回,是里面赋值才有数据。 INOUT 输入输出参数: 调用时指定,并且可被改变和返回。 在存储过程中,有可能会有多个结果产生,说明存储过程不是函数,如果是参数类型为out的这种,需要显示out结果的话,需要在存储过程执行完成后,select out_paramName来显示结果; 比如在存储过程中有多个select 查询语句,就会有多个结果集在存储过程执行后产生; */ -- 结束符修改,测试了一下,不用修改结束符也可以识别 delimiter // drop procedure if exists proc1 // create procedure proc1(out s int) begin select count(*) into s from data_region_month; select distinct point_code,point_name from data_point_month; select * from data_region_month; end // -- 改回默认结束符,测试了一下,不用修改结束符也可以识别,如果不修改的话,在上面一句的结束用分号结束 delimiter ; set @p_out=0; set @p_out=1; call proc1(@p_out); select @p_out; -- 如果需要在存储过程中使用游标,可以参考:https://blog.csdn.net/zhaofuqiangmycomm/article/details/88651446