插入到oracle数据库中,但是我不想重复三列

时间:2019-08-08 15:38:50

标签: sql oracle jdbc

我有此代码/查询可以成功运行(从Java,将数据插入到oracle表中)

String sqlInsert = "insert into TableName (CWT_ID,EMPLOYEE_EMAIL,TRAVEL_DATE,TRAVEL_FROM,EXPENSE_AMT,EXPENSE_CUR,ZIP_FILENAME,INVOICE_ID,INVOICE_LINE_NUMBER) " + "VALUES (sequenceName.NEXTVAL,?,?,?,?,?,?,?,?)";

((我稍后使用PreparedStatement将值分配给“?,?,?,?...”,但这与我的问题无关

但是,如果该行包含与已经/以前添加的另一行相同的ZIP_FILENAME,INVOICE_ID和INVOICE_LINE_NUMBER,则我试图弄清楚如何避免插入该行。

我该如何实现?

3 个答案:

答案 0 :(得分:0)

创建唯一索引或约束:

create unique index unq_tablename_3 on tablename(ZIP_FILENAME, INVOICE_ID, INVOICE_LINE_NUMBER);

答案 1 :(得分:0)

考虑将dualNOT EXISTS子查询一起使用。请注意:这需要为准备好的ZIP_FILENAME, INVOICE_ID, INVOICE_LINE_NUMBER值语句再添加三个参数:

String sqlInsert = "insert into TableName (CWT_ID, EMPLOYEE_EMAIL, TRAVEL_DATE, "
                 + "                       TRAVEL_FROM, EXPENSE_AMT, EXPENSE_CUR, "
                 + "                       ZIP_FILENAME, INVOICE_ID, INVOICE_LINE_NUMBER) "
                 + " select sequenceName.NEXTVAL, ?, ?, ?, ?, ?, ?, ?, ? "
                 + " from dual "
                 + " where not exists(select 1 from TableName "
                 + "                  where (ZIP_FILENAME = ? "
                 + "                    and  INVOICE_ID = ? "
                 + "                    and  INVOICE_LINE_NUMBER = ?));"

答案 2 :(得分:0)

MERGE into TableName dest
USING (select sequenceName.NEXTVAL,?,?,?,?,?,?,?,? from dual) src
ON (dest.ZIP_FILENAME=src.ZIP_FILENAME and dest.INVOICE_ID=src.INVOICE_ID 
       and dest.INVOICE_LINE_NUMBER=src.INVOICE_LINE_NUMBER)
when matched then update
set dest.CWT_ID=src.CWT_ID, dest.EMPLOYEE_EMAIL=src.EMPLOYEE_EMAIL,dest.TRAVEL_DATE=src.TRAVEL_DATE, 
    dest.TRAVEL_FROM=,dest.EXPENSE_AMT=,dest.EXPENSE_CUR=src.EXPENSE_CUR
when not matched then
insert VALUES (src.CWT_ID,src.EMPLOYEE_EMAIL,src.TRAVEL_DATE,src.TRAVEL_FROM,src.EXPENSE_AMT
              ,src.EXPENSE_CUR,src.ZIP_FILENAME,src.INVOICE_ID,src.INVOICE_LINE_NUMBER)