title: MySQL - How can I make a function atomic?
body: <p>I have this function in my DB</p>
  
  <pre><code>CREATE FUNCTION BookBed (pPaciente varchar(255),
                                  pHospital bigint(20)) RETURNS BOOLEAN
  BEGIN
  DECLARE NumLeitosDisponiveis INT;
  DECLARE vReservaOK  BOOLEAN;
  DECLARE dt TIMESTAMP;
  
   SET dt = (Select now());
   SET NumLeitosDisponiveis = (SELECT AVAILABLEBEDCOUNT FROM HOSPITAL WHERE ID = pHospital); 
  
  
   IF((SELECT NumLeitosDisponiveis) &gt; 0) THEN 
   BEGIN
    START TRANSACTION;
  
    INSERT INTO RESERVATION(PERSON, HOSPITAL, DATE) VALUES (pPaciente, pHospital, dt);
  
    UPDATE HOSPITAL
      SET AVAILABLEBEDCOUNT = AVAILABLEBEDCOUNT - 1 
      WHERE ID = pHospital;
  
      SET vReservaOk = true;
  
      commit;
   END;
    ELSE 
      SET vReservaOk = false;     
    END IF;
  
  
   RETURN vReservaOK;
  
  END;
  </code></pre>
  
  <p>In the if part of my if-else statement, I would like to perform all the operations in a atomic way.
  I wanted to use the START TRANSACTION command, but they are disallowed in functions and I couldn't find any other command to perform it.</p>
  
  <p>Are functions atomic by default?
  If not, is there any way I can implement it?</p>
  
  <p>Thanks,
  Oscar</p>
  
  <p><strong>EDIT: And if I have to use a function, is it possible to have transactions?</strong> </p>