编写mysql存储过程

mysql数据库与sqlserver有些区别。今天项目需要从mysql中取数据,做成分批返回的接口。因此需要写一个取数据的存储过程。由于以前一直在使用sqlserver,此次需要在mysql中去实现。期间走了N多弯路。在此记录一下,避免下次仍会浪费N多时间。同时也可以给需要的网友参考。

1.在sqlServer中使用begin 和 and 来块状语句。在mysql中是使用delimiter//  ......//delimiter来处理。注意“//”这个符号,是一定要用上了。我则开始以为是注释,没有加上。因此出错了。

2.在SqlServer中输入参数时,可以给参数默认值,这样在调用存储过程时,就不用给有默认值的参数。但在mysql中却不能给参数赋默认值。在其内部赋值是可以的。但仍需要传入该参数。解决的办法是给参数一个空字段的值。如""。然后在存储过程内部进行决断。同时,在SqlServer中参数名要加上@,而mysql中不用加上@。

3.在mysql中使用if then end if 这样的结构。根据需要,在end if 后面加上;号。

整个存储过程如下:

delimiter//

create procedure p_get_goods(in customid varchar(15),in goodscode varchar(15) ,in goodsName nvarchar(50),
in specification nvarchar(50),in mnemonic_code varchar(50),in pageIndex int,in pageSize int,out rowTotal int,out next int)
begin
declare firstrow int;
declare lastrow int;
if pageIndex = 1 then
if exists(select 1 from tb_Part_returns where id=customid and tableName='goods') then
delete from tb_Part_returns where id=customid and tableName='goods';
END IF;
set @x=0; 
set @sql=concat('insert into tb_Part_returns(id ,tableName ,autoid ,codes) ','select ''',customid ,''',''goods'',@x:=@x+1 as rownum,goods_code from ecp_product p,tb_manufacturers m where m.id=p.manufacturer');
if(length(goodscode)>0) then
set @sql=concat(@sql,' and ','goods_code like ''%',goodscode,'%''');
END IF;
if(length(goodsName)>0) then
set @sql=concat(@sql,' and ','full_name like ''%',goodsName,'%''');
END IF;
if(length(specification)>0) then
set @sql=concat(@sql,' and ','goods_specification like ''%',specification,'%''');
END IF;
if(length(mnemonic_code)>0)then
set @sql=concat(@sql,' and ','mnemonic_code like ''%',mnemonic_code,'%''');
END IF;
prepare cmdtext from   @sql;
execute cmdtext;
END IF;


select  autoid into rowTotal from tb_Part_returns where id=customid and tableName='goods' order by autoid desc limit 1;

set firstrow =(pageIndex-1) * pageSize + 1;
set lastrow = pageIndex * pageSize;
select goods_code,full_name,goods_specification,m.name as manufacturer,bar_code,
goods_common_name,standard_unit,approval_number,mnemonic_code
from ecp_product p,tb_manufacturers m,
(select codes from tb_Part_returns where id=customid and tableName='goods' and autoid between firstrow and lastrow) b
 where m.id=p.manufacturer and b.codes = p.goods_code ;

/**取走值就删除原值**/
delete from tb_Part_returns where id=customid and tableName='goods' and autoid between firstrow and lastrow;
if not exists(select 1 from tb_Part_returns where id=customid and tableName='goods') then
set next = 0 ;
else
set next = 1 ;
end if;
end
//
delimiter
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值