存儲過程:一組預先編譯好的sql語句的集合,理解成批處理語句。sql
create procedure 存儲過程名(參數列表) begin 存儲過程體(一組合法的sql語句) end
注意:數據庫
in stuname varchar(20);
delemiter 結束標記
語法:服務器
call 存儲過程名(實參列表);
delimiter $ create procedure myok() begin insert into admin(username,password) values ('john1','0000'),('lily','0000'),('rose','0000'),('jack','0000'),('tom','0000'); end $ call mypl()$
create procedure myp2(in beatuName varchar(20)) begin select bo.* from boys bo right join beauty b on bo.id=b.boyfriend_id where b.name=beautyName; end
案例2:用戶是否登陸成功函數
create procedure myp3(in username varhchar(10),in password varchar(20)) begin declare result int default 0; select count(*) into result from admin where admin.username=username and admin.password=password; select if(result >0,'成功','失敗); end $
delimiter $ create procedure myp5(in beautyName varchar(20),out boyName varchar(20)) begin select bo.boyName into boyName from boys bo inner join beauty b on bo.id = b.boyfriend_id where b.name=beautyName; end$ set @bNme$ call myp5('小昭',@bName)$ select @bName$
案例2:根據女神名,返回對於的男神名和男神魅力值code
delimiter $ create procedure myp6(in beautyName varchar(20),out boyName varchar(20),out userCP int) begin select bo.boyName ,bo.userCP into boyName,userCP from boys bo inner join beauty b on bo.id=b.boyfriend_id where b.name=beautyName; end $
create procedure myp8(inout a int,inout b int) begin set a=a*2 set b=b*2; end$
語法:drop procedure 存儲過程名
it
語法:show create procedure 存儲過程名;
io
與存儲過程基本相同,區別在於
存儲過程:能夠有0個返回,也能夠有多個返回,適合作批量插入,批量更新
函數:有且僅有一個返回,適合作 處理數據後返回一個結果。編譯
create function 函數名(參數列表) returns 返回類型 begin 函數體 end
注意:ast
SELECT 函數名(參數列表)
CREATE FUNCTION myf1() RETURNS INT BEGIN DECLARE c INT DEFAULT 0; SELECT COUNT(*) FROM employees; RETURN c; END
CREATE FUNCTION myf2(empName VARCHAR(20)) RETURNS DOUBLE BEGIN SET @sal=0; SELECT salary INTO @sal FROM employees WHERE last_name = empName; RETURN @sal; END$
案例2:根據部門名,返回該部門的平均工資function
CREATE FUNCTION myf3(deptName VARCHAR(20)) RETURNS DOUBLE BEGIN DECLARE sal DOUBLE; SELECT AVG(salary) INTO sal FROM employees e JOIN departments d ON e.department_id = d.department_id WHERE d.department_name=deptName; RETURN sal; END$
語法
show create function 函數名;
drop function 函數名;