简体   繁体   中英

Primary key violation while merging data from another table

I have two tables, TBTC03 and TBTC03Y, with TBTC03Y having two extra columns as EFFDTE and EXPDTE. I have to merge the data from TBTC03 to TBTC03Y with the following logic:

If no matching TC03 entry is found in TC03Y
a new TC03Y record is build with the TC03 data
the Effective Date will default to '01-01-1980'
the Expiration Date will default to '09-30-1995'

I wrote a query for the same as :

insert into  TBTC03Y (LOB,MAJPERIL,LOSSCAUSE,NUMERICCL,EFFDTE,EXPDTE)
    select LOB,MAJPERIL,LOSSCAUSE,NUMERICCL,'0800101' ,'0950930'
     from TBTC03 where not EXISTS (select * from TBTC03Y where 
TBTC03Y.LOB =        TBTC03.LOB AND 
TBTC03Y.MAJPERIL   = TBTC03.MAJPERIL   AND
TBTC03Y.LOSSCAUSE  = TBTC03.LOSSCAUSE  AND
TBTC03Y.NUMERICCL  = TBTC03.NUMERICCL)

The primary key for both the tables is LOB, MAJPERIL and LOSSCAUSE.

However i have some TBTC03Y records, that already have the data with the primary key.

Firing the above query gives primary key constraints on some of the rows. I am unable to figure out how i can acomplish it.

If the PK for both tables is {LOB, MAJPERIL, LOSSCAUSE} , you should remove TBTC03Y.NUMERICCL = TBTC03.NUMERICCL from your where clause.

Example:

t1{LOB, MAJPERIL, LOSSCAUSE, NUMERICCL}
   1    1         1          1

t2{LOB, MAJPERIL, LOSSCAUSE, NUMERICCL}
   1    1         1          2

In t2 there is no row where:

TBTC03Y.LOB =        TBTC03.LOB AND 
TBTC03Y.MAJPERIL   = TBTC03.MAJPERIL   AND
TBTC03Y.LOSSCAUSE  = TBTC03.LOSSCAUSE  AND
TBTC03Y.NUMERICCL  = TBTC03.NUMERICCL

But inserting will obvioulsy violate PK constraint in t2 :

t2{LOB, MAJPERIL, LOSSCAUSE}
   1    1         1 

The issue with the primary key is that you're also including NUMERICCL in the WHERE clause. If you remove this you'll then be inserting unique data.

You may have to create a separate process as it appears you have some records in each table that have the same LOB, MAJPERIL and LOSSCAUSE but have a different NUMERICCL. I can think of three options here;

  1. You have an issue with the data that needs fixing.
  2. Maybe you want to update this value to match, in which case you're looking at an UPDATE rather than INSERT INTO.
  3. You need to update your composite primary key to include the column NUMERICCL.
  4. Removing NUMERICCL from the where clause would also correct this.

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