开发者

DB2 v8 insert with CTE

开发者 https://www.devze.com 2023-01-15 19:39 出处:网络
I need to select from a CTE (common table expres开发者_如何学Csion) in DB2 v8 and insert the result into a table.

I need to select from a CTE (common table expres开发者_如何学Csion) 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?


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)
                       )
);


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消