Mysql存储过程知识,案例

Mysql存储过程知识,案例:

create procedure delete_setting(in p_settingid integer)

begin

	delete

	from	setting

	where	settingid=p_settingid;

end



select `name` from mysql.proc where db = 'your_db_name' and `type` = 'PROCEDURE'







show procedure status;



show create procedure proc_name;



show create function func_name;



局部变量



create  procedure test3(out number1 integer)

begin

declare number2 integer default 100;

set number1=number2;

end



call test(@number)



select @number#



默认值为标量子查询



create procedure test2(out ta integer)

begin

declare tt integer default (select count(*) from `setting`);

set ta=tt;

end



流程控制



IF



create procedure getMax(in p1 integer,in p2 integer,out p3 integer)

begin

	if p1>p2 then

		set p3 = p1;

	elseif p1<p2 then

		set p3 = p2;

	else

		set p3=0;

	end if;

end





fibonnaci



create procedure fibonnaci(inout n1 integer,inout n2 integer,inout n3 integer)

begin

set n3=n1+n2;

if n3>1000 then

	set n3 = n3-1000;

end if;

set n1=n2;

set n2=n3;

end



create procedure largest(out t char(30))

begin

	if (select count(*) from product)>(select count(*) from productcategory) then

		set t="product";

	elseif (select count(*) from product)<(select count(*) from productcategory) then

		set t="productcategory";

	else

		set t = "equal";

	end if;

end





create procedure small_exit(out p1 integer,out p2 integer)

begin 

	set p1 = 1;

	set p2 = 2;

	block1:begin

		leave block1;

		set p2 = 3;

	end;

	set p1=4;

end



WHILE  计算两个相差的年月日



create procedure age(

		in start_date date,

		in end_date   date,

		out years integer,

		out monthes integer,

		out days integer

		)

begin

	declare next_date,previous_date date;

	

	set years = 0;

	set previous_date=start_date;

	set next_date =start_date+interval 1 year;

	while next_date<end_date do

		set years = years+1;

		set previous_date = next_date;

		set next_date = next_date+ interval 1 year;

	end while;

	

	set monthes = 0;

	set next_date = previous_date + interval 1 month;

	while next_date<end_date do

		set monthes = monthes +1;

		set previous_date=next_date;

		set next_date = previous_date+interval 1 month;

	end while;

end



————————————————————————

调用存储过程

建表

create table players_with_parents

(playerno	integer not null primary key,

 father_playerno integer,

 mother_playerno integer);



alter table players_with_parents add constraint fk_1 

foreign key (father_playerno) references player_with_parents (playerno);



alter table players_with_parents add

foreign key (mother_playerno) references player_with_parents(playerno);



增加外键约束;



insert into players_with_parents values(9,null,null),(8,null,null),(7,null,null),(6,null,null),(5,null,null)

,(4,8,9),(3,6,7),(2,4,5),(1,2,3)



create procedure total_number_of_parents(in_playerno integer,inout number integer)

begin

	declare v_father,v_mother integer;

	set v_father = 

	(select father_playerno from players_with_parents where playerno=in_playerno);



	set v_mother = 

	(select mother_playerno from players_with_parents where playerno=in_playerno);

	

	if v_father is not null then

		call total_number_of_parents(v_father,number);

		set number = number+1;

	end if;

	

	if v_mother is not null then

		call total_number_of_parents(v_mother,number);

		set number = number+1;

	end if;

end

set @num=0;

set max_sp_recursion_depth=100;	

call total_number_of_parents(4,@num);

select @num;





select into 



create procedure total_setting(out p1 integer)

begin

	select count(*) into p1 from `setting`;

end



create procedure get_setting(out v_name varchar(60),out v_value varchar(60))

begin

	select `name`,`value` into v_name,v_value from setting limit 0,1;

end



create procedure showErr(out p integer)

begin

	set p=1;

	insert into `setting` (`settingid`,`name`)values(12,'vname');

	set p=2;

end



create procedure showErr(out p integer,out error integer)

begin

	declare continue handler for sqlstat '23000'

		set error = '200000';

	declare continue handler for sqlstat '23001';

		set error = '200001';

	set error = '000000';

	set p=1;

	insert into `setting` (`settingid`,`name`)values(12,'vname');

	set p=2;

end



declare continue handler for 1062 set error='23000';

declare continue handler for 1136 set error='21S01';



01 SQLWARING

02 NOT FOUND

SQLEXCEPTION 01,02以外的



create procedure addDate(out error char(5))

begin

	declare continue handler for sqlstate '23000' set error='23000';

	declare continue handler for sqlstate '21S01' set error='21S01';

	set error='00000';

	insert into `setting` values(15,'test','testValue',10);

end



declare non_unique condition for sqlstate '23000';

ddeclare continue handler for non_unique set error='23000';



同一块中,相同的错误,不能有两个或多个处理程序;



带有游标的存储过程

declare c_players cursor for select playerno from players;



create procedure number_of_players(out number integer)

begin

	declare a_playerno integer;

	declare found boolean default true;

	declare c_players cursor for select playerno from players;

	declare continue handler for not found set found=false;

	set number=0;

	open c_players;

	fetch c_players into a_playerno;

	while found do

		set number =number+1;

		fetch c_players into a_playerno;

	end while;

	close c_players;

end





create procedure number_of_setting(out number integer)

begin

	declare a_settingid integer;

	declare found boolean default true;

	declare c_settingids cursor for select settingid from setting;

	declare continue handler for not found set found=false;

	set number=0;

	open c_settingids;

	fetch c_settingids into a_settingid;

	while	found do

		set number=number+1;

		fetch c_settingids into a_settingid;

	end while;

	close c_settingids;

end



create procedure delete_older_than_30()

begin

	declare v_age,v_playerno,v_years,v_months,v_days integer;

	declare v_birth_date date;

	declare found boolean default true;

	declare c_players cursor for

		select playerno,birth_date from players;

	declare continue handler for not found set found=false;

	open c_players;

	fetch c_players into v_playerno,v_birth_date;

	while found do

		call age(v_birth_date,now(),v_years,v_months,v_days);

		if v_years>30 then

			delete from penalties where playerno=v_playerno;

		end if;

		fetch c_players into v_playno,v_birth_date;

	end while;

	close c_players;

end



commit,rollback,start transaction;





create function test(t1 integer,t2 integer) returns integer

begin

	return t1+t2;

end

Mysql存储过程知识,案例

查询数据库中的存储过程

方法一:

       select `name` from mysql.proc where db = 'your_db_name' and `type` = 'PROCEDURE'

方法二:

         show procedure status;

查看存储过程或函数的创建代码

show create procedure proc_name;
show create function func_name;

查询数据库中的存储过程和函数

方法一:

       select `name` from mysql.proc where db = 'your_db_name' and `type` = 'PROCEDURE'   //存储过程
       select `name` from mysql.proc where db = 'your_db_name' and `type` = 'FUNCTION'   //函数

方法二:

         show procedure status; //存储过程

        show function status;     //函数

查看存储过程或函数的创建代码

show create procedure proc_name;
show create function func_name;

查看视图

SELECT * from information_schema.VIEWS   //视图

SELECT * from information_schema.TABLES   //表

查看触发器

方法一:
语法:SHOW TRIGGERS [FROM db_name] [LIKE expr]
实例:SHOW TRIGGERS\G     //触发器

方法二:
对INFORMATION_SCHEMA数据库中的TRIGGERS表查询
mysql>SELECT * FROM triggers T WHERE trigger_name=”mytrigger” \G

在存儲過程中使用 表名做变量传递:

 

PREPARE stmt_name FROM preparable_stmt; 

EXECUTE stmt_name [USING @var_name [, @var_name] ...]; 

{DEALLOCATE | DROP} PREPARE stmt_name; 

 

下面是示例:

 

DROP PROCEDURE IF EXISTS `newtable`;  

CREATE PROCEDURE `newtable`(IN tname varchar(64))  

BEGIN  

SET @sqlcmd = CONCAT('CREATE TABLE ', tname, ' (id int NOT NULL AUTO_INCREMENT, name varchar(64) DEFAULT NULL, PRIMARY KEY (`id`))');  

PREPARE stmt FROM @sqlcmd;  

EXECUTE stmt;  

DEALLOCATE PREPARE stmt;  

END;  

call newtable('abc'); 

 再来一个示例:

create procedure ate(in t char(30))

begin

	set @s=concat("alter table ",t," engine=innodb");

	prepare stmt from @s;

	execute stmt;

	deallocate prepare stmt;

end

call ate('deal')#

  

看下面的示例:

mysql> SET @s = 'SELECT SQRT(POW(?,2) + POW(?,2)) AS hypotenuse'; 

mysql> PREPARE stmt2 FROM @s; 

mysql> SET @a = 6; 

mysql> SET @b = 8; 

mysql> EXECUTE stmt2 USING @a, @b; 

+------------+ 

| hypotenuse | 

+------------+ 

| 10 | 

+------------+ 

mysql> DEALLOCATE PREPARE stmt2; 

在sql中替换变量;

如果你的MySQL 版本是 5.0.7 或者更高的,你还可以在 LIMIT 子句中使用它,示例如下:

mysql> SET @a=1;mysql> PREPARE STMT FROM "SELECT * FROM tbl LIMIT ?"; 

mysql> EXECUTE STMT USING @a; 

mysql> SET @skip=1; SET @numrows=5; 

mysql> PREPARE STMT FROM "SELECT * FROM tbl LIMIT ?, ?"; 

mysql> EXECUTE STMT USING @skip, @numrows; 

使用 PREPARE 的几个注意点:
A:PREPARE stmt_name FROM preparable_stmt;预定义一个语句,并将它赋给 stmt_name ,tmt_name 是不区分大小写的。
B: 即使 preparable_stmt 语句中的 ? 所代表的是一个字符串,你也不需要将 ? 用引号包含起来。
C: 如果新的 PREPARE 语句使用了一个已存在的 stmt_name ,那么原有的将被立即释放! 即使这个新的 PREPARE 语句因为错误而不能被正确执行。
D: PREPARE stmt_name 的作用域是当前客户端连接会话可见。
E: 要释放一个预定义语句的资源,可以使用 DEALLOCATE PREPARE 句法。
F: EXECUTE stmt_name 句法中,如果 stmt_name 不存在,将会引发一个错误。
G: 如果在终止客户端连接会话时,没有显式地调用 DEALLOCATE PREPARE 句法释放资源,服务器端会自己动释放它。
H: 在预定义语句中,CREATE TABLE, DELETE, DO, INSERT, REPLACE, SELECT, SET, UPDATE, 和大部分的 SHOW 句法被支持。
I: PREPARE 语句不可以用于存储过程,自定义函数!但从 MySQL 5.0.13 开始,它可以被用于存储过程,仍不支持在函数中使用!

 

了解了PREPARE的用法,再用变量做表名就很容易了。不过在实际操作过程中还发现其他一些问题,比如变量定义,declare变量和set @var=value变量的用法以及参数传入的变量。

测试后发现,set @var=value这样定义的变量直接写在字符串中就会被当作变量转换,declare的变量和参数传入的变量则必须用CONCAT来连接。具体的原理没有研究。

EXECUTE stmt USING @a;这样的语句USING后面的变量也只能用set @var=value这种,declare和参数传入的变量不行。

另外php调用mysql存储过程的时候也碰到很多问题,总是出现PROCEDURE p can't return a result set in the given context这样的问题。

mysql存储过程基本函数

一.字符串类  

CHARSET(str) //返回字串字符集
CONCAT (string2  [,... ]) //连接字串
INSTR (string ,substring ) //返回substring首次在string中出现的位置,不存在返回0
LCASE (string2 ) //转换成小写
LEFT (string2 ,length ) //从string2中的左边起取length个字符
LENGTH (string ) //string长度
LOAD_FILE (file_name ) //从文件读取内容
LOCATE (substring , string  [,start_position ] ) 同INSTR,但可指定开始位置
LPAD (string2 ,length ,pad ) //重复用pad加在string开头,直到字串长度为length
LTRIM (string2 ) //去除前端空格
REPEAT (string2 ,count ) //重复count次
REPLACE (str ,search_str ,replace_str ) //在str中用replace_str替换search_str
RPAD (string2 ,length ,pad) //在str后用pad补充,直到长度为length
RTRIM (string2 ) //去除后端空格
STRCMP (string1 ,string2 ) //逐字符比较两字串大小,
SUBSTRING (str , position  [,length ]) //从str的position开始,取length个字符,
注:mysql中处理字符串时,默认第一个字符下标为1 ,即参数position必须大于等于1
mysql> select substring(’abcd’,0,2);
+———————–+
| substring(’abcd’,0,2) |
+———————–+
|                       |
+———————–+
1 row in set (0.00 sec)
mysql> select substring(’abcd’,1,2);
+———————–+
| substring(’abcd’,1,2) |
+———————–+
| ab                    |
+———————–+
1 row in set (0.02 sec)

TRIM([[BOTH|LEADING|TRAILING] [padding] FROM]string2) //去除指定位置的指定字符
UCASE (string2 ) //转换成大写
RIGHT(string2,length) //取string2最后length个字符
SPACE(count) //生成count个空格 

二.数学类

ABS (number2 ) //绝对值
BIN (decimal_number ) //十进制转二进制
CEILING (number2 ) //向上取整
CONV(number2,from_base,to_base) //进制转换
FLOOR (number2 ) //向下取整
FORMAT (number,decimal_places ) //保留小数位数
HEX (DecimalNumber ) //转十六进制
注:HEX()中可传入字符串,则返回其ASC-11码,如 HEX(’DEF’)返回4142143
也可以传入十进制整数,返回其十六进制编码,如HEX(25)返回19
LEAST (number , number2  [,..]) //求最小值
MOD (numerator ,denominator ) //求余
POWER (number ,power ) //求指数
RAND([seed]) //随机数
ROUND (number  [,decimals ]) //四舍五入,decimals为小数位数]
注:返回类型并非均为整数,如:
(1)默认变为整形值
mysql> select round(1.23);
+————-+
| round(1.23) |
+————-+
|           1 |
+————-+
1 row in set (0.00 sec)

mysql> select round(1.56);
+————-+
| round(1.56) |
+————-+
|           2 |
+————-+
1 row in set (0.00 sec)

(2)可以设定小数位数,返回浮点型数据 
mysql> select round(1.567,2);
+—————-+
| round(1.567,2) |
+—————-+
|           1.57 |
+—————-+
1 row in set (0.00 sec)

SIGN (number2 ) //返回符号,正负或0
SQRT(number2) //开平方

 
三.日期时间类

ADDTIME (date2 ,time_interval ) //将time_interval加到date2
CONVERT_TZ (datetime2 ,fromTZ ,toTZ ) //转换时区
CURRENT_DATE (  ) //当前日期
CURRENT_TIME (  ) //当前时间
CURRENT_TIMESTAMP (  ) //当前时间戳
DATE (datetime ) //返回datetime的日期部分
DATE_ADD (date2 , INTERVAL d_value d_type ) //在date2中加上日期或时间
DATE_FORMAT (datetime ,FormatCodes ) //使用formatcodes格式显示datetime
DATE_SUB (date2 , INTERVAL d_value d_type ) //在date2上减去一个时间
DATEDIFF (date1 ,date2 ) //两个日期差
DAY (date ) //返回日期的天
DAYNAME (date ) //英文星期
DAYOFWEEK (date ) //星期(1-7) ,1为星期天
DAYOFYEAR (date ) //一年中的第几天
EXTRACT (interval_name  FROM date ) //从date中提取日期的指定部分
MAKEDATE (year ,day ) //给出年及年中的第几天,生成日期串
MAKETIME (hour ,minute ,second ) //生成时间串
MONTHNAME (date ) //英文月份名
NOW (  ) //当前时间
SEC_TO_TIME (seconds ) //秒数转成时间
STR_TO_DATE (string ,format ) //字串转成时间,以format格式显示
TIMEDIFF (datetime1 ,datetime2 ) //两个时间差
TIME_TO_SEC (time ) //时间转秒数]
WEEK (date_time [,start_of_week ]) //第几周
YEAR (datetime ) //年份
DAYOFMONTH(datetime) //月的第几天
HOUR(datetime) //小时
LAST_DAY(date) //date的月的最后日期
MICROSECOND(datetime) //微秒
MONTH(datetime) //月
MINUTE(datetime) //分

 

附:可用在INTERVAL中的类型
DAY ,DAY_HOUR ,DAY_MINUTE ,DAY_SECOND ,HOUR ,HOUR_MINUTE ,HOUR_SECOND ,MINUTE ,MINUTE_SECOND,MONTH ,SECOND ,YEAR 
 
再说一个小技巧:
比如想要在存储过程中使用"show tables";
可以使用
" SELECT `table_name` FROM `information_schema`.`TABLES`  WHERE `TABLE_SCHEMA`= 'banksys'"
替换。因为show tables 的结果并不能像select的结果这样循环。

你可能感兴趣的:(Mysql存储过程)