Home > OS >  how to uniquely identify rows in two table copies
how to uniquely identify rows in two table copies

Time:01-09

I have essentially two tables that are copies of each other. One is dynamic and some DML statements happen quite constantly, so this table serve as a stage table, the other is used as a way to synchronize the changes form this stage table. So the tables can have different data at different times, and I use a merge statement to sync the tables. Something along these lines:

MERGE INTO source s
USING (
    SELECT
        * 
    FROM
        stage st
) se ON ( s.eim_product_id = st.eim_product_id )
...

The problem is that eim_product_id is neither a primary key, nor unique. So my merge statement essentially throws this error:

Error report -
ORA-30926: unable to get a stable set of rows in the source tables

And the only pseudo-columns I can think of to use is something like an identity column id_seq INTEGER GENERATED ALWAYS AS IDENTITY or a rowid. However, the problem is that it will not be consistent this approach to uniquely identify the row across both tables, right ? I believe I need some kind of hash that does the job , but unsure what would be the best and simplest approach in this case.

CodePudding user response:

The rowid pseudo-column won't match between the tables, and isn't necessarily constant. Creating a hash could get expensive in terms of CPU; an updated row in the first table wouldn't have a matching hash in the second table for the merge to find. If you only generate the hash at insert and never update then it's just a more expensive, complicated sequence.

Your best bet is an identity column with a unique constraint on the first table, copied to the second table by the merge: it is unique, only calculated very efficiently once at insert, will always identify the same row in both tables, and need never change.

  • Related