插入记录不存在的地方

时间:2018-05-02 07:01:57

标签: oracle insert not-exists ora-00001

INSERT INTO CUST_ID_HISTORY(CUST_ID,PREVIOUS_CUST_ID,UPDATE_DATE) 
SELECT CUST_ID,PREVIOUS_CUST_ID,UPDATE_DATE
FROM CUST_ID_HISTORY WHERE NOT EXISTS (SELECT 1 FROM CUST_ID_HISTORY WHERE
CUST_ID='SCB301' AND PREVIOUS_CUST_ID='SCB201');

以上查询在表中不存在插入值时向CUST_ID_HISTORY插入新记录。我遇到提供值的错误ORA-00001: unique constraint,但表中不存在这两个值。

2 个答案:

答案 0 :(得分:1)

您的语句从CUST_ID_HISTORY中选择并插入CUST_ID_HISTORY。换句话说,当CUST_ID != 'SCB301'PREVIOUS_CUST_ID != 'SCB201'没有记录时,它会尝试为 CUST_ID_HISTORY 中的每条记录创建重复记录。据推测这是表的主键,因此ORA-00001唯一密钥违规。

如果你想要实现的是在CUST_ID_HISTORY中为这些值插入一条记录,那么你可能需要一个合并语句。像这样:

merge into CUST_ID_HISTORY tgt
using ( select 'SCB301' as id, 'SCB201' as prev_id
         from dual ) src
on ( src.id = tgt.cust_id 
      and src.prev_id = tgt.prev_cust_id)
when not matched then
    insert (cust_id, prev_cust_id, update_date)
    values (src.id, src.prev_id, sysdate)
/

答案 1 :(得分:0)

查询:

INSERT INTO CUST_ID_HISTORY(CUST_ID,PREVIOUS_CUST_ID,UPDATE_DATE) 
SELECT CUST_ID,PREVIOUS_CUST_ID,UPDATE_DATE
FROM CUST_ID_HISTORY

将复制所有 CUST_ID_HISTORY表的行。

添加过滤器:

WHERE NOT EXISTS (
  SELECT 1
  FROM CUST_ID_HISTORY
  WHERE CUST_ID='SCB301' AND PREVIOUS_CUST_ID='SCB201'
);

如果行不存在,将检查表中是否存在CUST_ID='SCB301' AND PREVIOUS_CUST_ID='SCB201'的行,然后 all CUST_ID_HISTORY表中的行将被复制,如果如果存在这样的行,则该语句将插入零行。

因此,您的查询将复制所有行或不执行任何操作。

如果要插入一个新行,请检查它是否存在:

INSERT INTO CUST_ID_HISTORY(CUST_ID,PREVIOUS_CUST_ID,UPDATE_DATE) 
SELECT 'SCB301',
       'SCB201',
       SYSDATE   -- The current date/time
FROM   DUAL
WHERE NOT EXISTS (
  SELECT 1
  FROM CUST_ID_HISTORY
  WHERE CUST_ID='SCB301' AND PREVIOUS_CUST_ID='SCB201'
);

或:

MERGE INTO CUST_ID_HISTORY dst
USING (
  SELECT 'SCB301' AS CUST_ID,
         'SCB201' AS PREVIOUS_CUST_ID
  FROM   DUAL
) src
ON (   src.CUST_ID          = dst.CUST_ID
   AND src.PREVIOUS_CUST_ID = dst.PREVIOUS_CUST_ID )
WHEN NOT MATCHED THEN
  INSERT ( CUST_ID, PREVIOUS_CUST_ID, UPDATE_DATE ) 
  VALUES ( src.CUST_ID, src.PREVIOUS_CUST_ID, SYSDATE );

这将检查是否存在现有行,如果不存在则插入单行。