#函数
/**
含义:一组预先编译好的SQL语句的集合,理解成批处理语句
1.提高代码的重用性
2.简化操作
3.减少了编译次数并且减少了数据库服务器的连接次数,提高了效率
*/
create function f1() returns int
begin
return 0;
end
drop function f1
select f1()
#无参有返回
#案例:返回公司的员工个数
create function f2() returns int
begin
declare c int default 0;#定义局部变量
select count(*) into c from employees;
return c;
end
#删除函数
drop function f2
#调用函数
select f2() + 100
#有参有返回
#案例1:根据员工名,返回它的工资
create function f3(empName varchar(20)) returns double
begin
set @sal = 0;
select salary into @sal from employees where last_name = empName limit 1;
return @sal;
end
drop function f3
select f3(‘Fay’) - 14000 result
#案例2:根据部门名,返回该部门的平均工资
create function f4(deptName varchar(20)) returns double
begin
declare sal double;
select avg(salary) into sal
from employees e
inner join departments d on e.department_id = d.department_id
where department_name=deptName;
return sal;
end
drop function f4
select f4(‘IT’) + 10000 平均工资
#三.查看函数
show create function f4
#案例
#一.创建函数,实现传入两个float,返回二者之和
create function test_fun1(num1 float,num2 float) returns float
begin
declare sum float default 0;
set sum = num1 + num2;
return sum;
end
drop function test_fun1
select test_fun1(100,200)
create function f5() returns int
begin
#函数begin块中除了select必须要into外,别的都可以正常使用
insert into person(name,password) values(‘aaa001’,‘111111’);
return 0;
end
drop function f5
select f5()
#存储过程
/**
存储过程和函数:类似于java的方法
好处:
1.提高代码的重用性
2.简化操作
*/
/**
存储过程
含义:一组预先编译好的SQL语句的集合,理解成批处理语句
1.提高代码的重用性
2.简化操作
3.减少了编译次数并且减少了和数据库服务器的连接次数,提高了效率
参数模式:
in: 该参数可以作为输入,也就是该参数需要调用方传入值
out:该参数可以作为输出,也就是该参数可以作为返回值
inout:该参数即可以作为输入又可以作为输出,也就是该参数即需要传入值,又可以返回值
*/
#创建存储过程
create procedure p1()
begin
select ‘俄罗斯酸黄瓜’;
end
drop procedure p1
#调用存储过程
call p1()
#空参列表
#案例:插入到person表中五条记录
create table person(
id int primary key auto_increment,
name varchar(20),
password varchar(20)
)
delete from person
select * from person
create procedure p2()
begin
insert into person(name,password) values(‘aaa001’,‘111111’),(‘aaa002’,‘111111’),(‘aaa003’,‘111111’);
end
drop procedure p2
call p2()
#案例2:创建存储过程实现,用户是否登录成功
create procedure p3( name varchar(20), password varchar(20))
begin
declare result int default 0;#声明并初始化
select count(*) into result from person p where p.name=name and p.password=password;
select if(result>0,‘成功’,‘失败’) 结果;
end
drop procedure p3
call p3(‘aaa001’,‘111111’)