Corwin01
Corwin01

Reputation: 479

Oracle Merge. How can I use it?

I have this function:

      Procedure UpdateDefaultWeight  ( vYear Number, costWeight Number, qualityWeight Number, serviceWeight Number ) 
      AS

        type weight_table is table of Number(5,2) index by varchar2(50);
        weightArray weight_table;
        currentPosition varchar2(50);
      Begin

        weightArray('Cost Weighting')    := costWeight;
        weightArray('Quality Weighting') := qualityWeight;
        weightArray('Service Weighting') := serviceWeight;

        currentPosition := weightArray.first;

        Loop
          Exit When currentPosition is null;
          Insert Into GVS.GVSSD16_DFLT_WEIGHT
            ( cal_year, metric_name, metric_val )
          Values
            ( vYear, currentPosition, weightArray(currentPosition) ); 

          currentPosition := weightArray.next(currentPosition);
        End Loop;
      END;

Right now as I wrote it, it just does an INSERT. However, I need it to UPSERT. I've looked around at documentation on MERGE, but mainly it's just left me confused on how to apply the syntax to my specific case.

I've looked here and here and I get the jist of it, but syntax fails me.

Anyone care to help an Oracle newbie out?

Upvotes: 5

Views: 14154

Answers (1)

DCookie
DCookie

Reputation: 43553

Assuming that cal_year and metric_name define the join criteria, this should get you close (untested):

MERGE INTO GVS.GVSSD16_DFLT_WEIGHT d
     USING (SELECT vYear AS YY,
                   currentPosition AS POS,
                   weightArray (currentPosition) AS WA
              FROM DUAL) v
        ON (d.cal_year = v.YY AND d.metric_name = v.pos)
WHEN MATCHED
THEN
   UPDATE SET metric_val = v.WA
WHEN NOT MATCHED
THEN
   INSERT     (cal_year, metric_name, metric_val)
       VALUES (v.YY, v.POS, v.WA);

Upvotes: 6

Related Questions