我尝试使用游标对 mysql 8 上的某些表进行 运行 相同的查询。我不明白我的代码有什么问题
I am try to run same query on some tables on mysql 8 by using a cursor. I can not understand what is the problem in my code
我正在尝试 运行 对一些 table 进行相同的查询并从中检索数据,但是在 运行 查询之后它说 0 行受影响并且结果 table 为空。
我正在使用游标。
我无法得到什么问题
delimiter //
drop procedure if exists hunt //
create procedure hunt()
begin
DECLARE done int default false;
DECLARE table_name CHAR(255);
declare sqll longtext;
DECLARE cur1 cursor for SELECT TABLE_NAME FROM INFORMATION_SCHEMA.tables
WHERE TABLE_SCHEMA = "xyz_database" and table_name LIKE "%vendor%" ;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
open cur1;
myloop: loop
fetch next from cur1 into table_name;
if done then
leave myloop;
end if;
set sqll ='INSERT INTO Task1_AverageCapacities SELECT AVG(capacity) as AverageCapacity
FROM (SELECT cycle,MAX(mAh_transferred_during_discharging) as capacity
FROM'+table_name+' where cycle<101
GROUP BY cycle) AS avg_capacity;';
PREPARE stmt FROM @sqll;
EXECUTE stmt;
DEALLOCATE PREPARE stmt ;
end loop;
close cur1;
end //
delimiter ;
call hunt();
您需要使用 CONCAT()
函数进行字符串连接,而不是 +
运算符。
并且您需要在 FROM
和 table 名称之间添加一个 space。
set sqll = CONCAT('INSERT INTO Task1_AverageCapacities SELECT AVG(capacity) as AverageCapacity
FROM (SELECT cycle,MAX(mAh_transferred_during_discharging) as capacity
FROM ', table_name, ' where cycle<101
GROUP BY cycle) AS avg_capacity;');
并且变量的名称是sqll
,而不是@sqll
,所以你准备它:
PREPARE stmt FROM sqll;
我正在尝试 运行 对一些 table 进行相同的查询并从中检索数据,但是在 运行 查询之后它说 0 行受影响并且结果 table 为空。 我正在使用游标。 我无法得到什么问题
delimiter //
drop procedure if exists hunt //
create procedure hunt()
begin
DECLARE done int default false;
DECLARE table_name CHAR(255);
declare sqll longtext;
DECLARE cur1 cursor for SELECT TABLE_NAME FROM INFORMATION_SCHEMA.tables
WHERE TABLE_SCHEMA = "xyz_database" and table_name LIKE "%vendor%" ;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
open cur1;
myloop: loop
fetch next from cur1 into table_name;
if done then
leave myloop;
end if;
set sqll ='INSERT INTO Task1_AverageCapacities SELECT AVG(capacity) as AverageCapacity
FROM (SELECT cycle,MAX(mAh_transferred_during_discharging) as capacity
FROM'+table_name+' where cycle<101
GROUP BY cycle) AS avg_capacity;';
PREPARE stmt FROM @sqll;
EXECUTE stmt;
DEALLOCATE PREPARE stmt ;
end loop;
close cur1;
end //
delimiter ;
call hunt();
您需要使用 CONCAT()
函数进行字符串连接,而不是 +
运算符。
并且您需要在 FROM
和 table 名称之间添加一个 space。
set sqll = CONCAT('INSERT INTO Task1_AverageCapacities SELECT AVG(capacity) as AverageCapacity
FROM (SELECT cycle,MAX(mAh_transferred_during_discharging) as capacity
FROM ', table_name, ' where cycle<101
GROUP BY cycle) AS avg_capacity;');
并且变量的名称是sqll
,而不是@sqll
,所以你准备它:
PREPARE stmt FROM sqll;