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
查询数据库中的存储过程
方法一:
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这样的问题。
一.字符串类
TRIM([[BOTH|LEADING|TRAILING] [padding] FROM]string2) //去除指定位置的指定字符
UCASE (string2 ) //转换成大写
RIGHT(string2,length) //取string2最后length个字符
SPACE(count) //生成count个空格
二.数学类
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) //开平方
三.日期时间类
" SELECT `table_name` FROM `information_schema`.`TABLES` WHERE `TABLE_SCHEMA`= 'banksys'"