Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update statement using with clause

Tags:

sql

oracle

I have a script that uses a stack of with clauses to come up with some result, and then I want to write that result in a table. I just can't get my head around it, could someone point me in the right direction?

Here's a simplified example that indicates what i want to do:

with comp as (   select *, 42 as ComputedValue from mytable where id = 1 ) update  t set     SomeColumn = c.ComputedValue from    mytable t         inner join comp c on t.id = c.id  

The real thing has quite a few with clauses that all reference each other, so any suggestions actually using the with clause would be highly preferred over refactoring it to nested subqueries.

Thanks in advance,

Gert-Jan

like image 939
gjvdkamp Avatar asked Mar 21 '11 16:03

gjvdkamp


People also ask

Can we use with clause in update statement in SQL?

The real thing has quite a few with clauses that all reference each other, so any suggestions actually using the with clause would be highly preferred over refactoring it to nested subqueries. FYI: You don't have to edit your title and question to point out that you answered it yourself.

Can we use from clause in update statement in Oracle?

1 – Update with From JoinThis version of the Update statement uses a Join in the FROM clause. It's similar to other statements like Select and allows you to retrieve the value from one table and use it as a value to update in another table.

Can we use Order By clause in update statement?

If an UPDATE statement includes an ORDER BY clause, the rows are updated in the order specified by the clause. This can be useful in certain situations that might otherwise result in an error.

What does the update clause in an update statement do?

The UPDATE command in SQL is used to modify or change the existing records in a table. If we want to update a particular value, we use the WHERE clause along with the UPDATE clause. If you do not use the WHERE clause, all the rows will be affected.


1 Answers

If anyone comes here after me, this is the answer that worked for me.

NOTE: please make to read the comments before using this, this not complete. The best advice for update queries I can give is to switch to SqlServer ;)

update mytable t set z = (   with comp as (     select b.*, 42 as computed      from mytable t      where bs_id = 1   )   select c.computed   from  comp c   where c.id = t.id ) 

Good luck,

GJ

like image 143
gjvdkamp Avatar answered Sep 21 '22 12:09

gjvdkamp