MySQL stored procedure, handling multiple cursors and query results

前端 未结 5 1390

How can I use two cursors in the same routine? If I remove the second cursor declaration and fetch loop everthing works fine. The routine is used for adding a friend in my webap

5条回答
  •  猫巷女王i
    2021-02-14 08:58

    Here is a simple example of how to use two cursors in the same routine:

    DELIMITER $$
    
    CREATE PROCEDURE `books_routine`()
    BEGIN
      DECLARE rowCountDescription INT DEFAULT 0;
      DECLARE rowCountTitle INT DEFAULT 0;
      DECLARE updateDescription CURSOR FOR
        SELECT id FROM books WHERE description IS NULL OR CHAR_LENGTH(description) < 10;
      DECLARE updateTitle CURSOR FOR
        SELECT id FROM books WHERE title IS NULL OR CHAR_LENGTH(title) <= 10;
    
      OPEN updateDescription;
      BEGIN
          DECLARE exit_flag INT DEFAULT 0;
          DECLARE book_id INT(10);
          DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET exit_flag = 1;
    
          updateDescriptionLoop: LOOP
            FETCH updateDescription INTO book_id;
                IF exit_flag THEN LEAVE updateDescriptionLoop; 
                END IF;
                UPDATE books SET description = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.' WHERE books.id = book_id;
            SET rowCountDescription = rowCountDescription + 1;
          END LOOP;
      END;
      CLOSE updateDescription;
    
      OPEN updateTitle;
      BEGIN
          DECLARE exit_flag INT DEFAULT 0;
          DECLARE book_id INT(10);
          DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET exit_flag = 1;
    
          updateTitleLoop: LOOP
            FETCH updateTitle INTO book_id;
                IF exit_flag THEN LEAVE updateTitleLoop; 
                END IF;
                UPDATE books SET title = 'Lorem ipsum dolor sit amet' WHERE books.id = book_id;
            SET rowCountTitle = rowCountTitle + 1;
          END LOOP;
      END;
      CLOSE updateTitle;
    
      SELECT 'number of titles updated =', rowCountTitle, 'number of descriptions updated =', rowCountDescription;
    END
    

提交回复
热议问题