根据我的知识,光标的唯一用途是逐个从堆栈中为每个获取
选择值在shell脚本中,使用FOR或WHILE循环可以实现相同的效果。
示例:
while read ip;
do
echo $ip
done < ./test.txt
(OR)
IFS=$'\n'
for ip in $(cat ./test.txt)
do
echo "$ip"
done
如果test.txt有多行,那么一次迭代就会将一行加载到varible ip。
如何在没有游标和使用FOR(或)WHILE循环的mysql过程中实现相同的功能。
以下是使用游标的过程示例。我想在以下程序中应用解决方案。
delimiter $$
create procedure Replace_URL_IP()
begin
declare finished varchar(20);
declare ip varchar(20);
declare c1 cursor for select SUBSTRING_INDEX(SUBSTRING_INDEX(SUBSTRING_INDEX(VALUE,'/',3),'//',-1),':',1) IP from rbt_parameters where PARAM like '%URL%' and VALUE like 'http%';
declare continue handler for NOT FOUND set finished=1;
open c1;
start_loop: loop
fetch c1 into ip;
update rbt_parameters set value=replace(value,ip,'127.0.0.1') where PARAM like '%URL%' and VALUE like 'http%';
if finished=1 then
leave start_loop;
end if;
end loop;
close c1;
end
$$
答案 0 :(得分:1)
MySQL存储过程中没有for / while循环结构来迭代查询结果。您将使用游标显示示例,这是唯一的方法。有人要求使用更简单的语法(例如https://bugs.mysql.com/bug.php?id=68758),但到目前为止还没有为MySQL实现过。
也许你会发现用应用程序编程语言而不是MySQL存储过程编写代码会更有效率。说实话,我不喜欢MySQL存储过程,我不会使用它们。
在您显示的示例中,您可以在存储过程中使用的一种替代方法是使用UPDATE语句将更改应用于匹配集中的所有行:
UPDATE rbt_parameters
SET VALUE = REPLACE(VALUE,
SUBSTRING_INDEX(
SUBSTRING_INDEX(
SUBSTRING_INDEX(value, '/', 3),
'//', -1),
':', 1),
'127.0.0.1')
WHERE PARAM LIKE '%URL%' AND VALUE LIKE 'http%';