0

我正在尝试创建一个存储过程,它返回给定 id 的父母的所有 Id。这是我到目前为止所得到的,出于所有意图和目的,该表由两列组成,id 和 ParentID。当前代码的结果是它似乎没有从表中获取 ParentID,它只是尝试将传入的 id 两次添加到临时表中,然后失败。我哪里做错了?

CREATE PROCEDURE `mydb`.`Test` (IN id int)
BEGIN
DECLARE parentId INT;
DECLARE n INT;

  DROP TEMPORARY TABLE IF EXISTS _1067_parents;

 CREATE TEMPORARY TABLE _1067_parents (
node_id INT NOT NULL PRIMARY KEY
  );
set n = 0;
set parentId := id;

get_parents_loop: LOOP
     set parentId := (select ParentID from mydb.myTable where TDOID = parentId);

    IF parentId is NULL THEN
      LEAVE get_parents_loop;
    END IF;

    INSERT INTO _1067_parents(node_id) Values (parentId);

END LOOP get_parents_loop;

 SELECT *
    FROM _1067_parents;

end
4

1 回答 1

1

SQL小提琴

MySQL 5.5.30 架构设置

create table `MyTable`(`id` int primary key, `parentid` int)
//

insert `MyTable` (`id`, `parentid`) values
  (1, null), (2, 1), (3, 2)
//

CREATE PROCEDURE `Test` (IN cid int)
BEGIN
DECLARE parId INT;
DECLARE curId INT;

  DROP TEMPORARY TABLE IF EXISTS _1067_parents;

 CREATE TEMPORARY TABLE _1067_parents (
node_id INT NOT NULL PRIMARY KEY
  );

set curId := cid;
get_parents_loop: LOOP
    set parId := null;

    set parId = (select parentid from MyTable where id = curId);

    IF parId is NULL THEN
      LEAVE get_parents_loop;
    END IF;

    INSERT INTO _1067_parents(node_id) Values (parId);
    set curId := parId;

END LOOP get_parents_loop;


 SELECT *
    FROM _1067_parents;

end
//

show create procedure test;

查询 1

call test(3)

结果

| NODE_ID |
-----------
|       1 |
|       2 |
于 2013-03-22T21:56:08.743 回答