I’m writing my first procedure and ge an error. I’ve reduced the error to the delete line but unsure why. Can somebody spot the issue here? Is it the variable?
DROP PROCEDURE IF EXISTS MPT_PROC;
DELIMITER $$
CREATE PROCEDURE MPT_PROC
MODIFIES SQL DATA
BEGIN
#-- DECLARE statements
DECLARE v_user_id INT DEFAULT 0;
DECLARE no_more_rows BOOLEAN;
DECLARE v_loop_cntr INT DEFAULT 0;
DECLARE v_num_rows INT DEFAULT 0;
DECLARE c_userfiles CURSOR
FOR
SELECT distinct f.user_id
FROM MPT_STG_FILEUPLOAD f
WHERE f.status = 'A'; #-- Accepted
DECLARE CONTINUE HANDLER FOR NOT FOUND
SET no_more_rows = TRUE;
OPEN c_userfiles;
#-- Loop through each user_id found as pending
the_loop: LOOP
FETCH c_userfiles INTO v_user_id;
#-- Break out of the loop if
#-- 1) there were no records, or
#-- 2) we've processed them all.
IF no_more_rows THEN
CLOSE c_userfiles;
LEAVE the_loop;
END IF;
DELETE FROM MPT_STG_FILEUPLOAD s
WHERE s.user_id = v_user_id;
COMMIT; #--Commiting the changes for this user
END LOOP the_loop;
END IF;
END
DELIMITER ;
MySQL doesn’t allow you to provide an alias for a table you are deleting from in a DELETE statement.
And lose the pound signs as comment delimiters. The double dash are the standard for marking the beginning of a comment. It looks like you have an unmatched
END IFtowards the end of your procedure.If
user_idis not the primary key on that MPT_STG_FILEUPLOAD table, your procedure could be deleting rows that are NOT marked as “Accepted”. What if a user_id has two rows in that table, and one of the rows is marked as accepted, and the other is not. Did you want to delete both rows?It looks like you’ve got two variables declared that aren’t being referenced anywhere,
v_loop_cntrandv_num_rows, I’d recommend you comment them out if they aren’t needed.This entire procedure could be done more efficiently in a single SQL statement.