简体   繁体   中英

IBM DB2 9.7 common table expression with update

I am trying to:

  1. Select a row and name it CTE
  2. update some columns for that table CTE

I am implementing this using common table expression, but I cannot get it to work.

Begin
With CTE AS
(select * from MyTable where Column1 is null order by Column2 desc
(Update CTE
Set Column3= 1, Column4 = 1, Column5 = 1))
Commit;

I have tried to follow the DB2 specifications, but still having problems :)

Normally, the syntax for a CTE looks more like this. Pay attention to the parens.

With CTE AS
(
  select * from MyTable where Column1 is null order by Column2 desc
)
Update CTE
Set Column3= 1, Column4 = 1, Column5 = 1;

But this documentation suggests you can't use an UPDATE statement with a CTE.

You can define a common table expression wherever you can have a fullselect statement. For example, you can include a common table expression in a SELECT, INSERT, SELECT INTO, or CREATE VIEW statement.


Possible workaround

If the CTE isn't updatable, just remove the CTE, and write an UPDATE statement. You don't need ORDER BY at all here. This looks like an equivalent UPDATE statement.

update MyTable
set ...
where Column1 is null

How about this

UPDATE (
  SELECT * FROM MYTABLE WHERE COLUMN1 IS NULL ORDER BY COLUMN2 DESC
  FETCH FIRST 1 ROW ONLY
)
SET COLUMN3= 1, COLUMN4 = 1, COLUMN5 = 1;

or if you want more flexability, maybe my answer on this one How to Update Multiple Queries in optimized way in DB2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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