在phpMyadmin執行mysql存儲過程(實例)


創建一個簡單的存儲過程(示例)

DELIMITER $$
DROP PROCEDURE IF EXISTS TEST1$$

CREATE DEFINER=`root`@`localhost` PROCEDURE TEST1()
BEGIN

DECLARE i int(4);
DECLARE str varchar(100);
SET i = 1;
SET str = 'ag||gs||fg||fs';
UPDATE `testdb`.`tb` SET `msg` = str WHERE `tb`.`id` = 1;

END$$

DELIMITER ;

CALL TEST1();

mysql中split函數

在mysql中並沒有split函數,需要自己寫:

1)獲得按指定字符分割的字符串的個數:

DELIMITER $$

DROP FUNCTION IF EXISTS `sims`.`func_get_split_string_total`$$

CREATE DEFINER=`root`@`localhost` FUNCTION `func_get_split_string_total`(
f_string varchar(1000),f_delimiter varchar(5)
) RETURNS int(11)
BEGIN
declare returnInt int(11);
if length(f_delimiter)=2 then
return 1+(length(f_string) - length(replace(f_string,f_delimiter,'')))/2;
else
return 1+(length(f_string) - length(replace(f_string,f_delimiter,'')));
end if;
END$$

DELIMITER ;

  例:func_get_split_string_total('abc||def||gh','||')  結果為3  

2)得到第i個分割后的字符串。

DELIMITER $$

DROP FUNCTION IF EXISTS `sims`.`func_get_split_string`$$

CREATE DEFINER=`root`@`localhost` FUNCTION `func_get_split_string`(
f_string varchar(1000),f_delimiter varchar(5),f_order int) RETURNS varchar(255) CHARSET utf8
BEGIN
declare result varchar(255) default '';
set result = reverse(substring_index(reverse(substring_index(f_string,f_delimiter,f_order)),f_delimiter,1));
return result;
END$$

DELIMITER ;

   例如:func_get_split_string('abc||def||gh','||',2) 為def

3) 示例需求:A表中的一個字段值為1||2, 在select 時要通過和B字典表的關聯得到a,b

CREATE DEFINER=`root`@`localhost` FUNCTION `getDictName`(v_str varchar(100)) RETURNS varchar(100) CHARSET utf8
BEGIN

DECLARE i int(4);
DECLARE dictCode varchar(100);
DECLARE dictName varchar(100);
DECLARE returnStr varchar(100);

set i = 1;
set returnStr = '';

if(v_str is null or length(v_str)=0) then
return returnStr;
else

while i<=func_get_split_string_total(v_str,'||')
do
set dictCode = func_get_split_string(v_str,'||',i);

select names into dictName from sims_dd_dict where code = dictCode;

set returnStr = concat(returnStr,'',dictName);
set i = i+1;
end while;

set returnStr = subString(returnStr,2);
return returnStr;

end if;
END$$

4) 示例需求:

假設一張表tb
id name  msg
1  aaaa
2  bbbb
3  bbbb
4  cccc
5  dddd
我手頭現在已知 要插入更新的 msg 內容:
順序如下:

ag
gs
fg
fs
dg

怎么按id從開始到結束 批量更新到數據庫表

DELIMITER $$
DROP PROCEDURE IF EXISTS TEST1$$

CREATE DEFINER=`root`@`localhost` PROCEDURE TEST1()
BEGIN

DECLARE i int(4);
DECLARE str varchar(100);
SET i = 1;
SET str = 'ag||gs||fg||fs';
while i<=func_get_split_string_total(str,'||')
do

UPDATE `testdb`.`tb` SET `msg` = func_get_split_string(str,'||',i) WHERE `tb`.`id` = i;

set i = i+1;
end while;

END$$

DELIMITER ;

CALL TEST1();

  phpMyAdmin調用和生成MySQL的存儲過程以及CURSOR的應用:查看
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM