1
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,但表中不存在这两个值。

4

2 回答 2

1

您的语句从 CUST_ID_HISTORY 中选择并插入到 CUST_ID_HISTORY 中。换句话说,当 where 没有记录时,CUST_ID != 'SCB301'它会尝试为CUST_ID_HISTORYPREVIOUS_CUST_ID != 'SCB201'中的每条记录创建重复记录。推测这是表的主键,因此 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)
/
于 2018-05-02T07:08:22.723 回答
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'如果该行不存在,则表中的所有行都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 );

这将检查是否存在现有行并在不存在时插入单行。

于 2018-05-02T09:18:58.887 回答