title: Detect missing values in a (auto-incremented) sequence
body: <p>I have a 'Port' INT column, which it's supposed to range from 30000 to 50000.</p>
  
  <p>So, I have a Stored Procedure inserting values (Port is NOT NULL). So I have to choose 'manually' the value storing on that field. Problem is, altough I can insert incrementally (30000,30001,30002....) at a certain point some entries are deleted (it becames 30000, 30002, 30004.... ) so there are holes to be set.</p>
  
  <p>I need to place in my SP a way to fit those holes (on the example I have they are 30001,30003 ....). My problem is how to check within the SP, if a certain value is already 'ocuppied'.</p>
  
  <p>The I thought using LOOP from MySQL. Tried something like this:</p>
  
  <pre><code>CREATE PROCEDURE teste()
  BEGIN
  DECLARE p INT;
  DECLARE aux INT;
  SET p = 30000;
  
    label1: LOOP
  
      SELECT Port FROM Reg WHERE Port = p INTO aux;
  
      IF p = 50000 THEN
      LEAVE label1;
      END IF;
  
  
      IF aux IS NULL THEN -- aux-1 is not null, so I can verify the "next  miminum available position"
          aux = aux - 1;
          LEAVE label1;
  
      ELSE
          SET p = p + 1;
          ITERATE label1;
  
  
      END IF;
  
    END LOOP label1;
  
   RETURN aux;
  
  END $$
  </code></pre>
  
  <p>My problem is obtaining a result value. If I place that RETURN statement I get the info that is only allowed on a FUNCTION. And the result from the SELECT is always null when I end the Loop.</p>
  
  <p>What can I do?</p>