MySQL List the table name to select the cursor.

I want the procedure to execute the answertable and partid parameter in the select statement, but when I call it, it does not replace the parameter that can be changed using the value

call call updateTotalScores('quiz_participation', 'quiz_answer', 1)

returns an error: 1146 - Table 'quizdb.answertable' doesn't exist

passing id works, but passing the table name is not the same as passing the table name to select in

DECLARE cur1 CURSOR FOR SELECT SUM(`score`), SUM(`maxscore`) FROM answertable WHERE `idParticipation`=partid;

full procedure:

DELIMITER $$
CREATE PROCEDURE updateTotalScores(IN participationtable CHAR(64), IN answertable CHAR(64), IN partid INT)
BEGIN
 DECLARE done INTEGER DEFAULT 0;
 DECLARE sscore INTEGER DEFAULT 0;
 DECLARE smaxscore INTEGER DEFAULT 0;
 DECLARE cur1 CURSOR FOR SELECT SUM(`score`), SUM(`maxscore`) FROM answertable WHERE `idParticipation`=partid;
 DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

 OPEN cur1;
 REPEAT
  FETCH cur1 INTO sscore, smaxscore;
  UNTIL done = 1
 END REPEAT;
 CLOSE cur1;

 UPDATE participationtable SET `score`=sscore, `maxscore`=smaxscore WHERE `idParticipation`=partid;
END $$
DELIMITER ;

For completeness

the table name cannot be passed to the MySql cursor, at least not yet

http://forge.mysql.com/worklog/task.php?id=3433

answer below (slightly corrected)

DELIMITER $$

CREATE PROCEDURE updateTotalScores(IN participation_table VARCHAR(45), IN answer_table VARCHAR(45), IN part_id INT)
BEGIN
    SET @stmt_text=CONCAT("SELECT @score := SUM(`score`), @maxscore := SUM(`maxscore`) FROM ",
                         answer_table, " WHERE `idParticipation`=",  part_id);
    PREPARE stmt FROM @stmt_text;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;

    SET @stmt_text=CONCAT("UPDATE ", participation_table, 
                        " SET `score`=?, `maxscore`=? WHERE `idParticipation`=", part_id);
    PREPARE stmt FROM @stmt_text;
    EXECUTE stmt USING @score, @maxscore;
    DEALLOCATE PREPARE stmt;
END $$
+3
source share
1 answer

, .

, Dynamic SQL.

, , Dynamic SQL. , , .

, , , , , 2 .

  SET @stmt_text=CONCAT("SELECT @score = SUM(`score`), @maxscore=SUM(`maxscore`) FROM ",                
                         answertable, "WHERE `idParticipation`= ",  partid);
  PREPARE stmt FROM @stmt_text;
  EXECUTE stmt USING @a;

,

  SET @stmt_text=CONCAT("UPDATE", participationtable, " SET `score`=@score,  
                      `maxscore`=@maxscore WHERE `idParticipation`=", partid);

  PREPARE stmt FROM @stmt_text;
  EXECUTE stmt USING @a;

  DEALLOCATE PREPARE stmt;

. , . , , , .

+2

Source: https://habr.com/ru/post/1769499/


All Articles