查询:
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 );
这将检查是否存在现有行并在不存在时插入单行。