DB2 v8 insert with CTE

时光怂恿深爱的人放手 提交于 2019-12-25 07:59:24

问题


I need to select from a CTE (common table expression) in DB2 v8 and insert the result into a table. The relevant documentation for v8 is hard to understand at first glance, but for v9 there's a clear example (http://publib.boulder.ibm.com/infocenter/dzichelp/v2r2/index.jsp?topic=/com.ibm.db29.doc.apsg/db2z_createcte.htm):

INSERT INTO vital_mgr (mgrno)
WITH VITALDEPT (deptno, se_count)  AS
(
     SELECT deptno, count(*)
     FROM DSN8910.EMP
     WHERE job = 'senior engineer'
     GROUP BY deptno
)
SELECT    d.manager
FROM      DSN8910.DEPT d
         , VITALDEPT s
WHERE     d.deptno = s.deptno
          AND s.se_count  >  (
               SELECT  AVG(se_count)
               FROM    VITALDEPT
          );

It does not work in v8 though. How should it be written in v8?


回答1:


Write it like a boss

INSERT INTO vital_mgr 
(
    SELECT d.manager
    FROM SN8910.DEPT AS d
        INNER JOIN 
            (
                SELECT deptno, count(*)
                FROM DSN8910.EMP
                WHERE job = 'senior engineer'
                GROUP BY deptno
            ) AS s (deptno, se_count)
                ON d.deptno = s.deptno
    WHERE s.se_count > (
                            SELECT AVG(se_count)
                            FROM
                                (
                                    SELECT deptno, count(*)
                                    FROM DSN8910.EMP
                                    WHERE job = 'senior engineer'
                                    GROUP BY deptno
                                ) AS VITALDEPT (deptno, se_count)
                       )
);



回答2:


There's a simple workaround here that allows you to use an INSERT or UPDATE using a conventional WITH statement. This hack will work for INSERT on V8 or greater, and for UPDATE on V9 or greater.

There are other methods for V8 or greater, typically using sub-selects, but I find them to be unpractical due to their complexity.



来源:https://stackoverflow.com/questions/3681833/db2-v8-insert-with-cte

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!