简体   繁体   中英

Oracle - conditional merge on multiple columns

I am running a merge on a single table with the following query:

    MERGE INTO tbl rs
    USING 
    SELECT res.sid, res.eid, res.a, res.b, res.c, res.d, res.e /* ... */
    /* Merge magic here */
    WHEN MATCHED THEN
        UPDATE SET rs.a = res.a, rs.b = res.b, rs.c = res.c, rs.d = res.d, rs.e = res.e;

Now, when one column contains different data than the original the update would be run on all 5 columns in a given row. Is there a way to restrict the update to update only the columns which are different and leave out the columns without differing data?

This is not exactly what you asked for, but you could restrict the UPDATE to those rows with at least one changed value with a WHERE clause in your UPDATE:

MERGE INTO tbl rs
USING 
  (SELECT res.sid, res.eid, res.a, res.b, res.c, res.d, res.e /* ... */ )
ON ( /* Merge magic here */ )
WHEN MATCHED THEN    
UPDATE SET 
      rs.a = res.a, 
      rs.b = res.b, 
      rs.c = res.c, 
      rs.d = res.d, 
      rs.e = res.e
WHERE rs.a <> res.a 
   OR rs.b <> res.b 
   OR rs.c <> res.c 
   OR rs.d <> res.d 
   OR rs.e <> res.e;

(depending on your data / application logic, you might want to add extra checking for NULL values).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM