尝试通过Oracle数据库中的bash脚本将登台表中的数据插入到另一个表中时违反唯一约束

时间:2018-07-03 15:04:55

标签: sql database bash oracle

我使用SQL Loader将数据批量加载到登台表中(那里没有问题)。 但是我要插入数据的表没有任何元组,因为它抱怨通过bash脚本的唯一约束。

将数据插入主表有哪些修复方法?

主表模式

CREATE TABLE "SYSTEM"."DATA_SM_METRIC" 
(
    UNIQUE_ID   VARCHAR2(250 CHAR) NOT NULL,
    METRIC_REVIEW_CRITERION_DESC    VARCHAR2(250 CHAR) NOT NULL,
    METRICS_REVIEW_CRITERION_VALUE  VARCHAR2(250 CHAR) NOT NULL, 
    ENTITY_TYPE VARCHAR2(250 CHAR) NOT NULL,
    REVIEWCRITERIATYPE  VARCHAR2(25 CHAR) NOT NULL,
    CREATETIME DATE Default sysdate,                       
    CONSTRAINT DATA_SM_METRIC_PK PRIMARY KEY (UNIQUE_ID,METRIC_REVIEW_CRITERION_DESC,CREATETIME)   
) 
;

登台表架构

CREATE TABLE "SYSTEM"."DATA_SM_METRIC_STG" 
(
    UNIQUE_ID   VARCHAR2(250 CHAR) NOT NULL,
    METRIC_REVIEW_CRITERION_DESC    VARCHAR2(250 CHAR) NOT NULL,
    METRICS_REVIEW_CRITERION_VALUE  VARCHAR2(250 CHAR) NOT NULL, 
    ENTITY_TYPE VARCHAR2(250 CHAR) NOT NULL,
    REVIEWCRITERIATYPE  VARCHAR2(25 CHAR) NOT NULL,
    CREATETIME DATE Default sysdate,
    CONSTRAINT DATA_SM_METRIC_STG_PK PRIMARY KEY (UNIQUE_ID,METRIC_REVIEW_CRITERION_DESC,CREATETIME)                                        
)
;

Shell脚本如下:

#!/bin/ksh

DATAFILE=$1

SQLPATH=/u01/app/oracle/product/12.2/db_1/bin

SQLPLUS=$SQLPATH/sqlplus

SQLLOADER=$SQLPATH/sqlldr

echo "Start loading file into staging table ->sqlldr $DATAFILE"

$SQLLOADER userid=system/oracle@127.0.0.1:1521/orcl12c 
control=./$DATAFILE.ctl data=./$DATAFILE log=./$DATAFILE.log  
bad=./$DATAFILE.bad skip=1 errors=100
echo $?

$SQLPLUS -S system/oracle@//127.0.0.1:1521/orcl12c <<EOF | sed 1,3d  
select count(*) from data_sm_metric_stg;

INSERT INTO data_sm_metric(unique_id,metric_review_criterion_desc,metrics_review_criterion_value,entity_type,reviewcriteriatype)



SELECT unique_id,metric_review_criterion_desc,metrics_review_criterion_value,entity_type,reviewcriteriatype FROM data_sm_metric_stg;

select unique_id from data_sm_metric;
exit
EOF

错误:

INSERT INTO data_sm_metric(unique_id,metric_review_criterion_desc,metrics_review_criterion_value,entity_type,reviewcriteriatype)


 *
ERROR at line 1:
ORA-00001: unique constraint (SYSTEM.DATA_SM_METRIC_PK) violated

1 个答案:

答案 0 :(得分:0)

在不存在的条件下添加

INSERT INTO data_sm_metric
  (unique_id,
   metric_review_criterion_desc,
   metrics_review_criterion_value,
   entity_type,
   reviewcriteriatype)

  SELECT unique_id,
         metric_review_criterion_desc,
         metrics_review_criterion_value,
         entity_type,
         reviewcriteriatype
    FROM data_sm_metric_stg
        where not exists ( select 1 from data_sm_metric where
         stg.unique_id=d.unique_id and
          stg.METRIC_REVIEW_CRITERION_DESC=d.METRIC_REVIEW_CRITERION_DESC and
            stg.CREATETIME=d.CREATETIME
          )