Mysql
 sql >> Datenbank >  >> RDS >> Mysql

Wie funktioniert HANDLER FOR NOT FOUND und wofür wird es verwendet?

Ein HANDLER dient zum Abfangen von Ausnahmen.

Beim Lesen von einem Cursor wird beim Lesen über das Ende des Cursors hinaus ein NOT FOUND ausgegeben Ausnahme, anstatt einen endlosen Strom von NULL zurückzugeben , also müssen Sie diese Ausnahme abfangen.

DECLARE val1 INT DEFAULT NULL;
DECLARE done TINYINT DEFAULT FALSE;

DECLARE c1 CURSOR FOR SELECT id FROM t1;

-- when the NOT FOUND condition fires, "done" -- which defaults to FALSE -- will be set to true,
-- and since this is a CONTINUE handler, execution continues with the next statement.   

DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

OPEN c1;

my_loop: 
LOOP

  FETCH NEXT FROM c1 INTO val1; 
  IF done THEN -- this will be true when we are out of rows to read, so we go to the statement after END LOOP.
    LEAVE my_loop; 
  ELSE
    -- maybe do more stuff here
  END IF;
END LOOP;

-- procedure continues here...

Teilweise aus meinem Beispiel hier kopiert .