Hello. Faced a task and ask for help to solve it. So, it is necessary to delete the data about the employee, at the same time it is necessary to check whether there are no planned procedures for this employee, and if there are outstanding procedures, it is necessary to return its cost to the client’s account. I've been throwing something over here, but maybe there are some more acceptable options, because This request is looping.
CREATE PROCEDURE `RemovePersonnel`( -- Add the parameters for the stored procedure here id CHAR(36) ) BEGIN CREATE TEMPORARY TABLE temp AS (SELECT * FROM clientprocedures WHERE clientprocedures.IdPersonnel = id); WHILE EXISTS (SELECT Id FROM temp) DO SELECT @CostOldClientProcedure := temp.Cost, @IdOldClient := temp.IdClient, @DateClientProcedure := temp.Date FROM temp WHERE temp.Id = Id; IF (@DateClientProcedure > now()) THEN UPDATE client SET Balance = Balance + @CostOldClientProcedure WHERE client.Id = @IdOldClient; END IF; IF @@error_count = 0 THEN commit; ELSE rollback; END IF; DELETE FROM temp WHERE temp.Id = Id; END WHILE; DELETE FROM personnel WHERE personnel.Id = id; END