Problem With SQL ZERO ROWS AFFECTED (Procedure)

22 Views Asked by At

Good morning, I have a problem With SQL Code. I have a table named DIPART (which contains information related to departments) with two attributes: NUM_DIPART, which is the department number (key), and NUM_DIP, which is the number of employees per department.

I should now write an SQL procedure that checks the value of NUM_DIP for each department in the table. If it is greater than 3, it should be incremented by a value x provided as input to the procedure. If it is less than 3, it should be decremented by the same value.

Below is the procedure:

DELIMITER $$
CREATE PROCEDURE ModNumDip(IN VALORE INTEGER)
BEGIN
   DECLARE dip_id INT;
   DECLARE num_dip INT;
   DECLARE done INT DEFAULT FALSE;

   -- Declaration of cursor to iterate over departments
   DECLARE dip_cursor CURSOR FOR
       SELECT NUM_DIPART
       FROM DIPART;
    
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
   
   -- Opening the cursor
   OPEN dip_cursor;
   
   -- Loop to iterate over departments
   dip_loop: LOOP
       FETCH dip_cursor INTO dip_id;
       -- Exit loop if there are no more records
       
       IF done THEN
         LEAVE dip_loop;
       END IF;
        
       -- Update the number of employees for the department
      SELECT NUM_DIP INTO num_dip FROM DIPART WHERE NUM_DIPART=dip_id;
       
      IF (num_dip < 3) THEN
        UPDATE DIPART SET NUM_DIP = num_dip + VALORE ;
       ELSE 
        UPDATE DIPART SET NUM_DIP = num_dip - VALORE ;
      END IF;
      
   END LOOP;

   -- Closing the cursor
   CLOSE dip_cursor;
END $$
DELIMITER

CALL `ModNumDip`(5);

I tried to write the procedure, but it doesn't work because it seems unable to read the values of the tuples on the two specified attributes. In fact, after several internal selects within the procedure, what happens is that num_dip (a variable internal to the procedure) is null, as if the cursor in the FETCH row did not return the concrete value needed for the NUM_DIP select, or even that this select, regardless of the WHERE condition, returns all null values. Please help me.

In any case, after execution, it says 0 rows affected, so at this point, it doesn't even enter the if statements.

0

There are 0 best solutions below