MySql存储过程学习札记

MySql存储过程学习笔记

?

# 对于MySQL 5.0.45版本,需要重新定义一个输入结束标记符,如:delimiter //

# 在所有的存储过程中使用”;”作为每一条语句的结束标记

# 而每一条MySQL语句都必须使用”//”作为结束标记;

drop procedure if exists phelloworld //

create procedure phelloworld()

begin

select ‘Hello,World!’ as F;

end;

//

?

drop procedure if exists padd //

create procedure padd

(

a int,

b int

)

?

begin

declare c int;

if a is null then

set a = 0;

end if;

if b is null then

set b = 0;

end if;

set c = a + b;

select c as Sum;

end;

//

?

# 使用mysql变量调用存储过程

set @a = 10 //

set @b = 12 //

call padd(@a,@b) //

?

# 直接使用常量值调用存储过程

call padd(11,12) //

?

# 对数据库表进行操作

# 创建表

drop table if exists mapping //

create table mapping (

`cFieldID` smallint(5) unsigned not null,

`cFieldName` varchar(30) not null,

primary key(`cFieldID`)

)Engine=InnoDB default charset=utf8 //

?

insert into mapping values(1,’MarketValue’) //

insert into mapping values(2,’P/L’) //

insert into mapping values(3,’EName’) //

insert into mapping values(4,’Nominal’) //

insert into mapping values(5,’Chg’) //

?

# 写一个存储过程,往mapping表中插入一条记录,并返回当前记录的总数

drop procedure if exists paddmapping //

create procedure paddmapping (

out cnt int

)

begin

declare maxid int;

select max(cFieldID)+1 into maxid from mapping;

insert into mapping values(maxid,’Hello’);

select count(cFieldID) into cnt from mapping;

end //

?

# 定义一个包含输入输出参数的存储过程

drop procedure if exists pinoutmapping //

create procedure pinoutmapping (

in cfid int,

out cfnm varchar(30)

)

?

begin

select cFieldName into cfnm from mapping where cFieldID = cfid;

end;

//

?

# 在定义存储过程时使用输入参数:in inParam type

# 输入参数可以在存储过程中被修改,但是不能返回该输入参数的值

drop procedure if exists pinparam //

create procedure pinparam (

in inparam int

)

begin

select inparam;

# 在存储过程中改变输入参数的值

set inparam = 2;

select inparam;

end;

//

?

# 调用该存储过程之后再查看输入参数的值是否发生改变,虽然输入参数的值在存储过程中进行了修改

#?

?

#在定义存储过程时使用输出参数:out outParam type

#输出参数可以在存储过程中进行修改,且能返回该输出参数的值

drop procedure if exists poutparam //

create procedure poutparam (

out outparam int

)

begin

select outparam;

# 改变输出参数的值

set outparam = 3;

select outparam;

end;

//

?

# 在定义存储过程时使用inout参数:inout inoutParam type

# 在调用存储过程时指定参数值,可在存储过程中改变该参数值且能返回

drop procedure if exists pinoutparam //

create procedure pinoutparam (

inout inoutparam int

)

begin

select inoutparam;

# 在存储过程中改变inout参数的值

set inoutparam = 3;

# 查看在存储过程中改变后的参数值

select inoutparam;

end;

//

?

# 在存储过程中定义变量:declare vname [,vname2 …] vtype [default value]

# vtype是mysql中的数据类型:int,float,date,varchar(length)

# 变量赋值:set vname=value

drop procedure if exists pvarible //

create procedure pvarible ()

begin

declare uid int(8) defaul

MySql存储过程学习札记

相关文章:

你感兴趣的文章:

标签云: