mysql - 使用游标循环存储过程并将返回值存储到变量中
问题描述
我的查询应该在遍历表 table_a 的游标时检查 table_b 中是否存在值。如果 table_b 中存在值,则将值返回到变量 @yyy。
当我运行这个存储过程时,我应该得到一个返回 col2、col3、col1 的值。但它只返回 col2、col3。
在这个查询中,当我使用它时,into @yyy
我觉得它没有按需要的方式工作。不确定是什么问题。你能帮忙吗?
只需通过删除into @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;
推荐阅读
- r - 使用 sf 对象自定义 ggplot2 中的图例
- sql - SQL Server:快速而肮脏的数据验证查询?
- ios - 如何在带有 iOS 的 Google Analytics(分析)中设置自定义变量标签
- java - 安装应用程序后立即发送 FCM 注册
- c++ - 不确定如何修复“会员参考”错误
- selenium-webdriver - 如何使用 Python 获取 WebDriver 以删除汇合页面表中的现有值?
- ruby - 设置 Capybara 值的竞态条件
- python - NameError:全局名称“interfaceName”未定义,即使它是
- postgresql - Airflow PostgresHook 从未提交的插入语句返回 ID
- c++ - 查询 SDL_Surface 以获取像素颜色的效率