gpt4 book ai didi

mysql - 使用游标进行循环并将返回值存储到变量中的存储过程

转载 作者:行者123 更新时间:2023-11-29 17:36:29 25 4
gpt4 key购买 nike

我的查询应该在循环遍历表 table_a 的游标时检查 table_b 中是否存在值。如果 table_b 中存在值,则将值返回到变量@yyy。
当我运行这个存储过程时,我应该得到一个返回 col2,col3,col1 的值。但它只返回 col2, col3。
在此查询中,当我使用 into @yyy 时,我觉得它没有按需要的方式工作。不确定是什么问题。你能帮忙吗?
只需将删除到@yyy中,我就可以得到正确的结果,但我需要对变量@yyy进行更多更改,这就是为什么我需要将结果存储到其中.

Delimiter $$
DROP PROCEDURE IF EXISTS sp_test3;
CREATE PROCEDURE sp_test3()
BEGIN
DECLARE DONE INT DEFAULT 0;
DECLARE col1 varchar(255);
DECLARE curA CURSOR FOR SELECT a1 FROM table_a;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET DONE = 1;
OPEN curA;
SET @SQL_TXT = '';
while done = 0 do
fetch next from CurA into col1;
if done = 0 then
SET @xxx = CONCAT("select b1 into @yyy from table_b where b1 ='",
col1,"'");
PREPARE stmt_name FROM @xxx;
EXECUTE stmt_name;
DEALLOCATE PREPARE stmt_name;
SELECT @yyy;
END IF;
END WHILE;
close curA;
end
$$

创建下面的表脚本:

      create table table_a(a1 varchar(255));      
create table table_b(b1 varchar(255));

insert into table_a values('col2');
insert into table_a values('col3');
insert into table_a values('col5');
insert into table_a values('col1');

insert into table_b values('col2');
insert into table_b values('col3');
insert into table_b values('col4');
insert into table_b values('col1');

最佳答案

drop procedure if exists sp_test3;
drop table if exists table_b, table_a;

create table if not exists table_a(a1 varchar(255));
create table if not exists table_b(b1 varchar(255));

insert into table_a values ('col2');
insert into table_a values ('col3');
insert into table_a values ('col5');
insert into table_a values ('col1');

insert into table_b values ('col2');
insert into table_b values ('col3');
insert into table_b values ('col4');
insert into table_b values ('col1');

CREATE PROCEDURE sp_test3()
BEGIN
DECLARE DONE, DONE1 INT DEFAULT 0;
DECLARE col1 varchar(255);
DECLARE curA CURSOR FOR SELECT a1 FROM table_a;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET DONE = 1;
OPEN curA;
SET @SQL_TXT = '';
while done = 0 do
fetch next from CurA into col1;
if done = 0 then
BEGIN
DECLARE CONTINUE HANDLER FOR NOT FOUND SET DONE1 = 1;
SET @xxx = CONCAT("select b1 into @yyy
from table_b
where b1 = '", col1, "'");
PREPARE stmt_name FROM @xxx;
EXECUTE stmt_name;
DEALLOCATE PREPARE stmt_name;
if (DONE1 = 0) THEN
SELECT @yyy;
ELSE
SET DONE1 = 0;
END IF;
END;
END IF;
END WHILE;
close curA;
end;

关于mysql - 使用游标进行循环并将返回值存储到变量中的存储过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50243074/

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