这几天遇到一种业务场景,需要将A表和B表对比,如果主键相同则更新,否则将A表数据插入B表
完整SQL如下:
MERGE INTO DTMH_UCAP.UCAP_DEPT T1 USING ( -- 用T2的数据插入T1,T2中SELECT 需将后续用到的字段都列出
SELECT
A.UNIT_UNID,
A.UNIT_DIVISION_CODE,
A.UNIT_FULL_NAME,
A.UNIT_BELONG_NODE_UNID,
A.UNIT_ORDER_ID,
A.UNIT_CODE,
'1' AS DEPT_IS_ENABLED,
'1' AS DEPT_IS_BUSINESS
FROM
DTTYYH_CORE.UMC_UNIT A
) T2 ON ( T1.DEPT_UNID = T2.UNIT_UNID ) -- 使用两张表字段进行对比是否相同
WHEN MATCHED THEN -- 如果相同,则更新
UPDATE
SET T1.DEPT_NAME = T2.UNIT_FULL_NAME,
T1.DEPT_NAME_SPELL = T2.UNIT_DIVISION_CODE
WHEN NOT MATCHED THEN -- 如果不相同,则插入
INSERT (
T1.DEPT_UNID,
T1.DEPT_NAME_SPELL,
T1.DEPT_NAME,
T1.DEPT_BELONGTO,
T1.DEPT_SORT,
T1.DEPT_SERIAL_NUMBER,
T1.DEPT_IS_ENABLED,
T1.DEPT_IS_BUSINESS
)
VALUES
(
T2.UNIT_UNID,
T2.UNIT_DIVISION_CODE,
T2.UNIT_FULL_NAME,
T2.UNIT_BELONG_NODE_UNID,
T2.UNIT_ORDER_ID,
T2.UNIT_CODE,
T2.DEPT_IS_ENABLED,
T2.DEPT_IS_BUSINESS
);