Geschachtelte Cursorn in Mysql
Ich habe drei Tabellen.
Projekt(Id), ein Attribut(Id), project_attribute(Id, project_id, attribute_id).
Möchte ich für das erstellen von Datensätzen in project_attribute Tabelle mit allen Attributen aus Attribut Tabelle zu jedem Projekt von Projekt Tabelle.
Zur Erstellung solcher Datensätze verwende ich folgende Prozedur speichern.
DELIMITER $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `proj_attr`()
BEGIN
DECLARE proj_done, attribute_done BOOLEAN DEFAULT FALSE;
declare attributeId int(11) default 0;
declare projectId int(11) default 0;
DECLARE curProjects CURSOR FOR SELECT id FROM project order by id;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET proj_done = TRUE;
OPEN curProjects;
cur_project_loop: LOOP
FETCH FROM curProjects INTO projectId;
IF proj_done THEN
CLOSE curProjects;
LEAVE cur_project_loop;
END IF;
BLOCK2: BEGIN
DECLARE curAttribute CURSOR FOR SELECT id FROM attribute order by id;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET attribute_done = TRUE;
OPEN curAttribute;
cur_attribute_loop: LOOP
FETCH FROM curAttribute INTO attributeId;
IF attribute_done THEN
CLOSE curAttribute;
LEAVE cur_attribute_loop;
END IF;
insert into project_attribute_value(project_id, attribute_id)
values(projectId, attributeId);
END LOOP cur_attribute_loop;
END BLOCK2;
END LOOP cur_project_loop;
END$$
DELIMITER ;
Aber dieses Verfahren ist die Erstellung von Datensätzen nur für 1 Projekt in project_attribute Tisch, obwohl es sind 50 Projekte in der Projekt-Tabelle. Erwartete Anzahl der Datensätze count(projektid)*count(attributeId).
Du musst angemeldet sein, um einen Kommentar abzugeben.
Versuchen, diese, dies wird sicherlich lösen Ihr Problem.
IF proj_done THEN set proj_done = false;
sollte sich ändern, umattribute
Ganz unverblümt, nested Cursor (in der Regel) eine schreckliche Idee. Sie können bekommen, was Sie wollen, direkt, ohne Verwendung eines Cursors, mit einer normalen
CROSS JOIN
.Nach der ersten iteration innerhalb der inneren cursor "attribute_done" - variable wird auf "true" gesetzt. Und es bleibt "wahr" für alle weiteren Iterationen.
Dies bewirkt, dass alle weiteren Iterationen zu überspringen, die innere Schleife.
Einer Probe nested cursor ist unten dargestellt.