bertrand
bertrand

Reputation: 13

Merge and source table multiple matches

I face a problem with the following query:

merge into table2 d
using (
  select firstname, lastname, max(id) id
  from table1 t1
  group by firstname, lastname
  having count(0) = 1
) s
on (d.firstname=s.firstname and d.lastname=s.lastname)
when matched then update set t1_id = s.id;

If multiple rows in table2 match the ON clause, then I get "SQL Error: ORA-30926: unable to get a stable set of rows in the source tables"

Do you know any way to filter and just ignore those "duplicates"? Thanks.

EDIT

@Polppan, your request for sample data has lead me on a very strange way:

here some sample data:

table1
ID       firstname     lastname
1        John          Doe
2        John          DOE
3        Jane          Doe
4        Jane          Doe

(notice the UPPER)

table2
t1_ID    firstname     lastname
null     John          Doe
null     Jane          Doe
null     Jane          Doe

now, I couldn't reproduce the error with those data until:

Any idea why?

Upvotes: 0

Views: 1469

Answers (1)

Jacob
Jacob

Reputation: 14731

Try using DISTINCT

MERGE INTO   table2 d
      USING  (SELECT     DISTINCT ((firstname))fname, ((lastname))lname,max(id) id
                        FROM     table1 t1
                        GROUP BY   firstname, lastname
                     HAVING  COUNT (0) = 1
                  ) s
          ON     ( upper(d.firstname) = upper(fname)
                  AND upper(lastname) = upper(lname))
WHEN MATCHED
THEN
    UPDATE SET id = s.id;

Update 1

MERGE INTO   table2 d
      USING  (SELECT     DISTINCT upper((firstname))fname, upper((lastname))lname,max(id) id
                        FROM     table1 t1
                        GROUP BY   firstname, lastname
                     HAVING  COUNT (0) = 1
                  ) s
          ON     ( upper(d.firstname) = upper(fname)
                  AND upper(lastname) = upper(lname))
WHEN MATCHED
THEN
    UPDATE SET id = s.id;

Upvotes: 1

Related Questions