简体   繁体   English

如何更改此db2合并查询?

[英]How to change this db2 merge query?

can someone help me? 有人能帮我吗? i am trying to convert the following merge into another query and i am allowed only to use insert and update once: 我正在尝试将以下合并转换为另一个查询,并且只允许使用一次插入和更新:

MERGE INTO MYEMPLOYEE ME USING EMPLOYEE E ON ME.EMPNO = E.EMPNO 
WHEN MATCHED THEN 
UPDATE SET ME.SALARY = CASE WHEN ME.SALARY > E.SALARY THEN ME.SALARY ELSE E.SALARY END 
WHEN NOT MATCHED THEN 
INSERT VALUES(E.EMPNO, E.FIRSTNME, E.MIDINIT, E.LASTNAME, E.WORKDEPT, E.PHONENO, E.HIREDATE, E.JOB, E.EDLEVEL, E.SEX, E.BIRTHDATE, E.SALARY, E.BONUS, E.COMM);

How can I achieve this? 我该如何实现? the above merge copies the data if not exists, and if it exists it checks for the salary and selects the higher one and copies that one. 上述合并将复制数据(如果不存在),如果存在,则将检查薪水并选择较高的薪水并复制该薪水。 how can I achieve the same thing by only using one insert and one update? 如何仅使用一次插入和一次更新就可以达到相同的目的? Can someone give me hints, please? 有人可以给我提示吗?

Thanks in advance :) 提前致谢 :)

The purpose of the MERGE command is suppose to take into account multiple actions of UPDATE , INSERT , DELETE . 假设MERGE命令的目的是考虑UPDATEINSERTDELETE多个动作。 MERGE statement explained 合并说明

If you cannot/unable to use MERGE , then you have to resort to doing each request individually. 如果您不能/无法使用MERGE ,那么您必须求助于单独执行每个请求。

UPDATE MYEMPLOYEE ME
  SET ME.SALARY = (
    SELECT CASE WHEN ME.SALARY > E.SALARY THEN ME.SALARY ELSE E.SALARY END 
    FROM EMPLOYEE E 
    WHERE ME.EMPNO = E.EMPNO
 )
 WHERE EXISTS(
   SELECT 1 
   FROM EMPLOYEE E 
   WHERE ME.EMPNO = E.EMPNO
 );

Then do an insert where the employee don't exist in the master table. 然后在主表中不存在该雇员的地方进行插入。

INSERT INTO MYEMPLOYEE ME
  SELECT * 
  FROM EMPLOYEE E 
    LEFT OUTER JOIN MYEMPLOEE ME ON E.EMPNO=ME.EMPNO
  WHERE ME.EMPNO IS NULL;

If you need to do in one full sweep you can use the IMPORT command. 如果需要进行一次完整扫描,则可以使用IMPORT命令。 But then you are dealing with files. 但是随后您正在处理文件。 You would need to export the EMPLOYEE table (probably with salary already formatted) and then import using the INSERT_REPLACE ability. 您将需要导出EMPLOYEE表(可能已经格式化了薪水),然后使用INSERT_REPLACE功能导入。

After trying I noticed that the INSERT code should actually be like this: 尝试之后,我注意到INSERT代码实际上应该是这样的:
1) Don't use the Name ME twice 1)不要重复使用Name ME
2) Select the necessary columns because after the join there are twice the column count 2)选择必要的列,因为连接后列数是两倍

INSERT INTO MYEMPLOYEE (
    SELECT E.EMPNO, E.FIRSTNME, E.MIDINIT, E.LASTNAME, E.WORKDEPT, E.PHONENO, E.HIREDATE, E.JOB, E.EDLEVEL, E.SEX, E.BIRTHDATE, E.SALARY, E.BONUS, E.COMM 
    FROM EMPLOYEE E LEFT OUTER JOIN MYEMPLOYEE ME ON E.EMPNO = ME.EMPNO WHERE ME.EMPNO IS NULL
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM