函数与存储过程相似,也是一组预先编译好的SQL语句的集合,可是存储过程能够有0个或多个返回,函数就只能有一个返回sql
#语法 参数列表包含两部分 参数名和参数类型 #函数体必须有return语句 且每一个sql语句后要以;结尾 因此须要使用delimiter来从新设置结束标记 #函数体中只有一句话时能够省略begin end create function 函数名(参数列表) returns 返回值类型 begin 函数体 end
select 函数名(参数列表)
show create function 函数名;
drop function 函数名;
delimiter $ create function myfunc(class_name varchar(20)) returns int begin declare c int default 0; #设置局部变量,做为返回值 select count(s.id) into c # 将查询结果赋给局部变量 from class c join student s on c.id = s.classid where c.name = class_name; return c; #返回 end $ delimiter ; select myfunc('计算机一班');#函数调用
特别提醒一下:我在建立函数的时候出错了less
ERROR 1418 (HY000): This function has none of DETERMINISTIC, NO SQL, or READS SQL DATA in its declaration and binary logging is enabled (you might want to use the less safe log_bin_trust_function_creators variable)函数
须要设置一下code
set global log_bin_trust_function_creators=TRUE;
因为自己的博客百度没有收录,博客地址http://zhhll.icuget