How does HANDLER FOR NOT FOUND work and what is its usage?

前端 未结 1 569
迷失自我
迷失自我 2021-01-29 08:27

Still kinda new to MySQL. I was wondering what is HANDLER FOR NOT FOUND, how does it work and most importantly: what is its usage?

相关标签:
1条回答
  • 2021-01-29 08:59

    A HANDLER is for catching exceptions.

    When reading from a cursor, reading past the end of the cursor throws a NOT FOUND exception, rather than returning an endless stream of NULL, so you have to catch this exception.

    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...
    

    Copied in part from my example here.

    0 讨论(0)
提交回复
热议问题