在oracle中插入主键表的多表

jucafojl  于 2021-07-26  发布在  Java
关注(0)|答案(3)|浏览(388)

我尝试使用一个表将数据插入到不同的表中,并且我要插入的表具有主键。
有人能指导我如何改正错误吗?

INSERT
ALL
WHEN TO_CHAR(L_SHIPDATE,'YYYY') = '1995' THEN
 INTO YEAR1995
  VALUES (L_PARTKEY, L_EXTENDEDPRICE - 0.1*L_EXTENDEDPRICE)
WHEN TO_CHAR(L_SHIPDATE,'YYYY') = '1996' THEN
 INTO YEAR1996
  VALUES (L_PARTKEY, L_EXTENDEDPRICE - 0.1*L_EXTENDEDPRICE)
WHEN TO_CHAR(L_SHIPDATE,'YYYY') = '1997' THEN
 INTO YEAR1997
  VALUES (L_PARTKEY, L_EXTENDEDPRICE - 0.1*L_EXTENDEDPRICE)

SELECT distinct L_PARTKEY, L_EXTENDEDPRICE, L_SHIPDATE 
FROM LINEITEM;

第1行出错:ora-00001:违反了唯一约束(tpchr.year95\ u pkey)
这是表格定义

CREATE TABLE YEAR1995
(
    Y95_PARTKEY NUMBER(12) NOT NULL,
    Y95_PRICE   NUMBER(12) NOT NULL,
    CONSTRAINT YEAR95_PKEY PRIMARY KEY (Y95_PARTKEY, Y95_PRICE)  
);
mqxuamgl

mqxuamgl1#

正如本文所建议的,您可以尝试以下方法:

exec dbms_errlog.create_error_log ('myInsertErrors');

INSERT
ALL
WHEN TO_CHAR(L_SHIPDATE,'YYYY') = '1995' THEN
 INTO YEAR1995
  VALUES (L_PARTKEY, L_EXTENDEDPRICE - 0.1*L_EXTENDEDPRICE)
WHEN TO_CHAR(L_SHIPDATE,'YYYY') = '1996' THEN
 INTO YEAR1996
  VALUES (L_PARTKEY, L_EXTENDEDPRICE - 0.1*L_EXTENDEDPRICE)
WHEN TO_CHAR(L_SHIPDATE,'YYYY') = '1997' THEN
 INTO YEAR1997
  VALUES (L_PARTKEY, L_EXTENDEDPRICE - 0.1*L_EXTENDEDPRICE)

SELECT distinct L_PARTKEY, L_EXTENDEDPRICE, L_SHIPDATE 
FROM LINEITEM

LOG ERRORS INTO err$_myInsertErrors REJECT LIMIT UNLIMITED;

这样,所有插入异常(即重复数据)都将存储在 err$_myInsertErrors 表和insert语句

uemypmqf

uemypmqf2#

你的 l_shipdate 不是唯一的,因此您的查询在同一年内获得多个结果。您可以将年份提取移到查询:

INSERT
ALL
WHEN T_YEAR = 1995 THEN
 INTO YEAR1995
  VALUES (L_PARTKEY, L_EXTENDEDPRICE - 0.1*L_EXTENDEDPRICE)
WHEN T_YEAR = 1996 THEN
 INTO YEAR1996
  VALUES (L_PARTKEY, L_EXTENDEDPRICE - 0.1*L_EXTENDEDPRICE)
WHEN T_YEAR = 1997 THEN
 INTO YEAR1997
  VALUES (L_PARTKEY, L_EXTENDEDPRICE - 0.1*L_EXTENDEDPRICE)

SELECT distinct extraxt(YEAR from L_SHIPDATE) AS T_YEAR, L_PARTKEY, L_EXTENDEDPRICE
FROM LINEITEM;

由于每个价格的计算都是相同的,因此您也可以在查询中这样做:

INSERT
ALL
WHEN T_YEAR = 1995 THEN
 INTO YEAR1995
  VALUES (L_PARTKEY, T_EXTENDEDPRICE)
WHEN T_YEAR = 1996 THEN
 INTO YEAR1996
  VALUES (L_PARTKEY, T_EXTENDEDPRICE)
WHEN T_YEAR = 1997 THEN
 INTO YEAR1997
  VALUES (L_PARTKEY, T_EXTENDEDPRICE)

SELECT distinct extraxt(YEAR from L_SHIPDATE) AS T_YEAR,
  L_PARTKEY,
  0.9 * L_EXTENDEDPRICE AS T_PRICE
FROM LINEITEM;

我建议您在语句中也包含目标表的列名:

INSERT
ALL
WHEN T_YEAR = 1995 THEN
 INTO YEAR1995 (Y95_PARTKEY, Y95_PRICE)
  VALUES (L_PARTKEY, T_EXTENDEDPRICE)
...
lb3vh1jj

lb3vh1jj3#

您还需要了解什么是复制密钥才能理解此错误:

$ oerr ora 0001
00001, 00000, "unique constraint (%s.%s) violated"
// *Cause: An UPDATE or INSERT statement attempted to insert a duplicate key.
//         For Trusted Oracle configured in DBMS MAC mode, you may see
//         this message if a duplicate entry exists at a different level.
// *Action: Either remove the unique restriction or do not insert the key.
$

请参阅《oracle数据库概念指南》中有关独特约束的内容。

相关问题