Rac*_*cso 3 sql oracle with-statement sql-update
Is there any way to do some kind of "WITH...UPDATE" action on SQL?
For example:
WITH changes AS
(...)
UPDATE table
SET id = changes.target
FROM table INNER JOIN changes ON table.id = changes.base
WHERE table.id = changes.base;
Run Code Online (Sandbox Code Playgroud)
Some context information: What I'm trying to do is to generate a base/target list from a table and then use it to change values in another table (changing values equal to base into target)
Thanks!
您可以使用merge相当于您的with子句作为using子句,但因为您正在更新您正在加入的字段,您需要做更多的工作; 这个:
merge into t42
using (
select 1 as base, 10 as target
from dual
) changes
on (t42.id = changes.base)
when matched then
update set t42.id = changes.target;
Run Code Online (Sandbox Code Playgroud)
..给出错误:
ORA-38104: Columns referenced in the ON Clause cannot be updated: "T42"."ID"
Run Code Online (Sandbox Code Playgroud)
当然,这取决于你在CTE中所做的一些事情,但只要你能加入到你的表中就可以得到rowid你可以使用它来on代替:
merge into t42
using (
select t42.id as base, t42.id * 10 as target, t42.rowid as r_id
from t42
where id in (1, 2)
) changes
on (t42.rowid = changes.r_id)
when matched then
update set t42.id = changes.target;
Run Code Online (Sandbox Code Playgroud)
如果我t42使用id列创建我的表并且具有值为1,2和3的行,则会将前两个更新为10和20,并将第三个更新为单独的.
它不一定是rowid,如果它唯一地标识行,它可以是真正的列; 通常这将是一个id,通常永远不会改变(作为主键),你只是不能使用它并同时更新它.