gpt4 book ai didi

mysql - 执行查询结果语句

转载 作者:可可西里 更新时间:2023-11-01 07:23:25 25 4
gpt4 key购买 nike

我有一组名为 results_% 的表,它们都具有相同的结构。

我想为这个表添加一个索引。

我可以将每个表的 alter 语句作为选择查询结果的一行,但我不知道如何执行此语句:

select concat( 'alter table ', test_db.table_name, ' add index `did` (`did`);' ) as statement 
from information_schema.tables test_db
where test_db.table_name like 'results_%';

我错过了什么?

输出(我想执行而不是只显示给我):

+---------------------------------------------------------+
| statement |
+---------------------------------------------------------+
| alter table results_Em7777_spa add index `did` (`did`); |
| alter table results_KaEng_eng add index `did` (`did`); |
| alter table results_Ka_spa add index `did` (`did`); |
| alter table results_Mc_spa add index `did` (`did`); |
| alter table results_Mo_eng add index `did` (`did`); |
| alter table results_Pe_eng add index `did` (`did`); |
| alter table results_SU_spa add index `did` (`did`); |
| alter table results_Ta_spa add index `did` (`did`); |
| alter table results_ba_eng add index `did` (`did`); |
| alter table results_br_eng add index `did` (`did`); |
| alter table results_ca_spa add index `did` (`did`); |
| alter table results_ch_spa add index `did` (`did`); |
| alter table results_da_spa add index `did` (`did`); |
| alter table results_ga_eng add index `did` (`did`); |
| alter table results_ge_spa add index `did` (`did`); |
| alter table results_gk_eng add index `did` (`did`); |
+---------------------------------------------------------+
16 rows in set (0.00 sec)

[编辑]

我试过:

drop procedure if exists altlike; 
delimiter //
create procedure altlike()
begin
set group_concat_max_len = 65535;
select @altrlk:= concat( 'alter table ', test_db.table_name , ' add index `did` (`did`);' )
from information_schema.tables test_db
where test_db.table_name like "results_%";
prepare statement from @altrlk;
execute statement;
end //
delimiter ;
call altlike();

但仍然没有运气:它只改变了最后一个匹配的表 (results_gk_eng)。

最佳答案

drop procedure if exists `altlike`; 
DELIMITER //
CREATE PROCEDURE `altlike` ()
BEGIN
DECLARE a,c VARCHAR(256);
DECLARE b INT;
DECLARE cur1 CURSOR FOR select concat(test_db.table_name)
from information_schema.tables test_db
where test_db.table_name like 'results_%';
DECLARE CONTINUE HANDLER FOR NOT FOUND SET b = 1;
DECLARE CONTINUE HANDLER FOR 1061 SET b = 0;
OPEN cur1;
SET b = 0;
WHILE b = 0 DO
FETCH cur1 INTO a;
IF b = 0 THEN
SET @c = concat ('ALTER IGNORE TABLE `', a, '` ADD INDEX `did` (`did`)');
PREPARE stmt1 FROM @c;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;
END IF;
END WHILE;
CLOSE cur1;
END //
call altlike();

关于mysql - 执行查询结果语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9955732/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com