I didn't want to hijack this thread: {thread:id=2321156} so I thought I'd start a new one.
Scenario
Update a table, based on complex business conditions.
Approach 1
Single, monolithic UPDATE statement with multiple conditions (pseudo-code)
UPDATE some_table
SET some_col = some_val
WHERE col_a = val_x
AND EXISTS( -- complex correlated query )
AND NOT EXISTS ( -- complex correlated query )
...
AND EXISTS( -- complex correlated query )
Approach 2
Cursor FOR LOOP (pseudo-code)
DECLARE
t BOOLEAN;
BEGIN
FOR r IN ( SELECT *
FROM some_table
WHERE col_a = val_x
)
LOOP
t := check_complex_condition_a(r.pk);
t := check_complex_condition_b(r.pk);
t := check_complex_condition_c(r.pk);
t := check_complex_condition_d(r.pk);
IF t
THEN
UPDATE some_table
SET some_col = some_val
WHERE pk = r.pk
;
END IF;
END LOOP;
END;
Assumptions
1. Lets suppose the database design is satisfactory (3NF or BCNF)
2. Lets suppose in this example that the FOR LOOP approach runs
significantly faster (as in wall clock time) than the single UPDATE assignment.
3. Approach 1 and 2 are both implemented as optimally as possible.
Questions
After one has validated that the FOR LOOP is faster do you move on? Or is there another approach that you use to avoid the FOR LOOP approach? If so, what?
I know cursor FOR LOOPs are not to be spoken of around here ;) so I thought I'd bring up the question to see what you've all done in the past.
Edited by: Centinul on Dec 14, 2011 11:09 AM