Disregard if using MERGE INTO is better in this case or not. I just wonder if I can check if the row exists or not. If not, then set the return code to 1 and return immediately. If yes, then continue to execute the rest of code and set return code to 0 in the end. Below code is not working as it always executes to the end. How should I fix it?
BEGIN
-- check
SELECT CASE
WHEN NOT EXISTS (SELECT 1 FROM s WHERE s.col1 = 1 AND s.col2 = 2)
THEN 1
END
INTO ret FROM dual;
-- update
UPDATE s
SET s.col3 = 3
WHERE s.col1 = 1 AND s.col2 = 2;
COMMIT;
SELECT 0 INTO ret FROM dual;
RETURN ret;
END foo;
What if I want be able to distinguish if it’s s.col1 = 1 not exist or s.col2 = 2 not exist. And have 2 different return codes for them. How should I do in this case?
You are not doing anything with the value stored
ret.There is no
IFaround the UPDATE statement that checks if ret is 1 or null (the other alternative). And because there is no IF the rest of the procedure is always executed.Something like this is needed:
A much more efficient approach is to simply do the update and check if any rows where modified. Running the select before doing the update simply doubles the work if the row exists. Running only the update when the row does not exist is the same work as doing the select.