带有 while 循环的嵌套游标

Nested cursors with while loop

我想用 while 循环编写一个嵌套游标,这样当 Table_A 的 column_name 匹配 Table_B 的 col1 时,我可以从 table_B 获得结果。
如果 select col1, col2, col3 from Table_B where col1 = tblA_col1 is null then go to next row and return col1.
我需要将列结果保存在变量中。

  Delimiter $$
  DROP PROCEDURE IF EXISTS sp_test;
  CREATE PROCEDURE sp_test() 
  begin 
    DECLARE done, done1 int DEFAULT 0; 
    DECLARE tblA_col1 varchar(255); 
    DECLARE tblB_col1 varchar(255);
    DECLARE tblB_col2 varchar(255);
    DECLARE tblB_col3 varchar(255);
      DECLARE curA CURSOR FOR   SELECT column_name   FROM   Table_A; 
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1; 
    open curA; 

      WHILE (done = 0) do
      FETCH next   FROM  curA   INTO  tblA_col1;
     DECLARE curB CURSOR FOR   select col1, col2, col3 from Table_B where col1 = tblA_col1;
      DECLARE CONTINUE HANDLER FOR NOT FOUND SET done1 = 1; 
      open curB;
    Fetch next from curB into tblB_col1,tblB_col2,tblB_col3;
    select tblB_col1;
   select tblB_col2;
    select tblB_col3;
    close curB;
  if tblB_col1 is null then 
  tblB_col1 = tblB_col1;
  end if;

    end while;
    close curA;
    end;
    $$
  --  call sp_test

我是游标的新手,在使用嵌套的 curB 时遇到问题。你能帮忙吗?

我注意到的唯一明显的语法问题是循环中的 DECLARES。

DECLARE is permitted only inside a BEGIN ... END compound statement and must be at its start, before any other statements.

https://dev.mysql.com/doc/refman/8.0/en/declare.html

如果您在第一次提取后放置 BEGIN,在关闭 curB 后放置 END,您没有准确指定 having 的问题可能会得到解决。您可能还需要在每次外部迭代时重置 done1(我不记得它是否保留了先前迭代的值。)