一:字符串拆分方法 (类似java中split()与PaAdmin库中的split_part()函数)
CREATE DEFINER=`root`@`%` PROCEDURE `p_test`(IN `pnames` varchar(50))
BEGIN
-- pnames = 'a,b,c,d,e,f'
DECLARE _z_end int DEFAULT 0;
DECLARE _z_num int DEFAULT -1;
DECLARE _z_str varchar(50);
DECLARE _name varchar(50);
-- 创建临时表
DROP TABLE IF EXISTS p_test_msg;
create TEMPORARY table p_test_msg(
code varchar(50),
msg varchar(50)
);
set _z_str := SUBSTRING_INDEX(pnames,',',_z_num);
set _z_num = -1 + _z_num;
set _name:= SUBSTRING_INDEX(pnames,',',1) ;
while(_z_end <> -1) do
-- 插入临时表
insert into p_test_msg(code,msg) values(_z_num,_name);
set _z_str := SUBSTRING_INDEX(pnames,',',_z_num);
set _z_num = -1 + _z_num;
if(_z_str = pnames) then
set _z_end := -1;
end if;
set _name:= SUBSTRING_INDEX(_z_str,',',1) ;
end while;
SELECT * FROM p_test_msg;
END
二:存储过程中游标的使用
CREATE DEFINER=`root`@`%` PROCEDURE `p_demo`()
BEGIN
DECLARE name VARCHAR(32);
DECLARE phone VARCHAR(32);
DECLARE password VARCHAR(32);
-- 游标
DECLARE s int DEFAULT 0;
DECLARE temp CURSOR FOR SELECT a.user_name,a.user_tel,a.login_pwd from t_pm_user a ;
DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET s = 1;
-- 创建临时表
DROP TABLE IF EXISTS p_demo_msg;
create TEMPORARY table p_demo_msg(
code varchar(50),
msg varchar(50)
);
OPEN temp;
FETCH temp into name,phone,password;
while s<>1 do
-- 插入临时表
insert into p_demo_msg(code,msg) values(name,phone);
FETCH temp into name,phone,password;
END WHILE;
CLOSE temp;
SELECT * FROM p_demo_msg;
END
三:存储过程中执行用字符串拼成的sql语句
DROP PROCEDURE IF EXISTS test_prepareStam;
CREATE PROCEDURE test_prepareStam(IN id int)
BEGIN
TRUNCATE TABLE test_table;
/*
-- 直接拼sql 然后prepare EXECUTE
set @exeSql=concat("INSERT INTO test_table (id, val, uv, visitor_val, visitor_uv)VALUES (",id);
set @exeSql=concat(@exeSql,", 3,4,6,7)");
-- select @exeSql;
prepare stmt from @exeSql;
EXECUTE stmt;
deallocate prepare stmt;
*/
/*
-- 直接拼sql+? 然后prepare EXECUTE+using
set @_id=id;
set @exeSql=concat("INSERT INTO test_table (id, val, uv, visitor_val, visitor_uv)VALUES (?, 3,4,6,7)");
prepare stmt from @exeSql;
EXECUTE stmt using @_id; -- 多个用逗号隔开
deallocate prepare stmt;
*/
-- *********存储过程执行用字符串拼成的sql语句 *********
set @exeSql = ' INSERT INTO test_table (id, val, uv, visitor_val, visitor_uv)VALUES (111, 3,4,6,7) '; -- 注意很重要,将连成成的字符串赋值给一个变量(可以之前没有定义,但要以@开头)
prepare stmt from @exeSql; -- 预处理需要执行的动态SQL,其中stmt是一个变量
EXECUTE stmt; -- 执行SQL语句
deallocate prepare stmt; -- 释放掉预处理段
select * from test_table;
END;