MySQL自定义函数与存储过程_MySQL 中的自定义函数和存储过程 简单实例

本文介绍了在MySQL中如何在存储过程中处理SELECT结果集,利用临时表存储和传递。详细展示了如何创建和调用存储过程及函数,包括参数的输入输出,并提供了实际的示例代码,如变量交换、条件判断等,帮助读者理解MySQL中的存储过程和函数操作。
摘要由CSDN通过智能技术生成

需要说明的是:MySQL中没有表变量, 一般是通过临时表来存贮结果集的。

那么 我们如何取出在储存过程中select出来的结果集呢?如果是其它存储过程中,你可以使用生成的临时表。如果是java程序中,你可以直接象执行select * from aa一样调用call xxx();的结果

--MySQL 中的函数

-- 函数 返回int类型

DELIMITER $$

DROP FUNCTION IF EXISTS `switchnum`$$

create FUNCTION switchnum()

RETURNS int

begin

declare v_xx int default null;

declare v_yy int default 1;

declare v_zz int default 2;

set v_xx=v_yy;

set v_yy=v_zz;

set v_zz=v_xx;

return v_zz;

end $$

DELIMITER ;

select switchnum();

----MySQL中的存储过程

-- 创建存储过程 传入int类型的参数

delimiter ;

drop procedure if exists getUserInfo;

create PROCEDURE getUserInfo (in us int)

begin

if (us is not null) then

set us=2;

end if;

end ;

set @us=4;

call getUserInfo( @us);

select @us as tempus;

-- 创建存储过程 传入varchar 类型的参数

delimiter;

drop procedure if exists getvarchar;

create procedure getvarchar( in ad varchar(20))

begin

if (ad is not null) then

select * from tb_users where username=ad;

else

select * from tb_users;

end if;

end ;

set @ad=null;

call getvarchar(@ad);

select @ad;

-- 测试

drop procedure if exists pr_param_inout;

create procedure pr_param_inout

(

inout id int

)

begin

select id as id_inner_1; -- id 值为调用者传进来的值

if (id is not null) then

set id = id + 1;

select id as id_inner_2;

else

select 1 into id;

end if;

select id as id_inner_3;

end;

set @inout=2;

call pr_param_inout(@inout);

select @inout as in_out;

-- ---测试procedure

delimiter;

DROP PROCEDURE IF EXISTS text;

create procedure text(

out rtn int

)

begin

declare LoginId INT default 0;

set rtn=1;

IF LoginId = 3

THEN

set rtn=2;

ELSEIF LoginId = 0

THEN

set rtn=3;

ELSE

set rtn=4;

END IF;

end ;

call text(@rtn);

select @rtn as rtn;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值